Python List Basic Flashcards

1
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you create a list named my_list with the elements 1, 2, 3 in Python?

A

```python
my_list = [1, 2, 3]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you access the first element of the list nums = [10, 20, 30]?

A

```python
nums[0] # Returns 10
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Given fruits = ["apple", "banana", "cherry"], how do you change the value of “banana” to “orange”?

A

```python
fruits[1] = “orange”
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you append the integer 5 to numbers = [1, 2, 3, 4]?

A

```python
numbers.append(5)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Given colors = ["red", "green", "blue"], how do you add “yellow” as the second element, using a list method?

A

```python
colors.insert(1, “yellow”)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Given letters = ["a", "b", "c", "d"], how do you remove “c” from the list by its value?

A

```python
letters.remove(“c”)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Given nums = [1, 2, 3], how do you remove and return the last element using a list method?

A

```python
popped_value = nums.pop() # Returns 3
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Given nums = [1, 2, 3, 4], how do you remove and return the element at index 1 using a list method?

A

```python
popped_value = nums.pop(1) # Removes and returns 2
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you concatenate list1 = [1, 2] and list2 = [3, 4] into [1, 2, 3, 4] using the + operator?

A

```python
combined = list1 + list2
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Given list1 = [1, 2] and list2 = [3, 4], how do you extend list1 so it becomes [1, 2, 3, 4]?

A

```python
list1.extend(list2)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you slice the first 3 elements from nums = [10, 11, 12, 13, 14]?

A

```python
slice_part = nums[:3] # [10, 11, 12]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you slice nums = [10, 20, 30, 40, 50] to get [30, 40] using Python slice notation?

A

```python
slice_part = nums[2:4] # [30, 40]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you get every second element from nums = [1, 2, 3, 4, 5, 6] using slicing?

A

```python
every_second = nums[::2] # [1, 3, 5]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Given my_list = [2, 4, 6, 8], how do you reverse the list in-place (so that my_list becomes [8, 6, 4, 2])?

A

```python
my_list.reverse()
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you reverse a list nums = [1, 2, 3] without modifying the original list (using slicing)?

A

```python
reversed_list = nums[::-1] # [3, 2, 1]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Given numbers = [4, 2, 6, 1], how do you sort it in ascending order in-place?

A

```python
numbers.sort()
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you sort numbers = [4, 2, 6, 1] in descending order in-place?

A

```python
numbers.sort(reverse=True)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you create a sorted copy of nums = [3, 1, 2] without modifying nums itself?

A

```python
sorted_copy = sorted(nums)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Given nums = [1, 2, 3], how do you double every value and return a new list using a list comprehension?

A

```python
doubled = [x * 2 for x in nums] # [2, 4, 6]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you filter out odd numbers and keep only even numbers from nums = [1, 2, 3, 4, 5, 6] using a list comprehension?

A

```python
evens = [x for x in nums if x % 2 == 0] # [2, 4, 6]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Given words = ["apple", "banana", "cherry"], how do you create a list of their lengths using a list comprehension?

A

```python
lengths = [len(word) for word in words] # [5, 6, 6]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you check if the list my_list = [2, 4, 6] is empty or not, in a Pythonic way?

A

```python
if not my_list:
print(“Empty list”)
else:
print(“Not empty”)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Given nums = [5, 3, 1, 4, 2], how do you find the smallest value using a built-in function?

A

```python
minimum = min(nums) # 1
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Given `nums = [5, 3, 1, 4, 2]`, how do you find the largest value using a built-in function?
```python maximum = max(nums) # 5 ```
26
How do you calculate the sum of all elements in `nums = [1, 2, 3, 4]` using a built-in function?
```python total = sum(nums) # 10 ```
27
Given `my_list = [1, 2, 3]`, how do you check if the element `2` is in `my_list` using an operator?
```python if 2 in my_list: print("2 is found") ```
28
Given `my_list = [1, 2, 3]`, how do you check if the element `5` is not in `my_list` using an operator?
```python if 5 not in my_list: print("5 is not found") ```
29
How do you determine the index of the value `4` in `nums = [1, 2, 4, 2, 4]` using a list method?
```python index_of_4 = nums.index(4) # 2 ```
30
How do you count how many times the value `2` appears in `nums = [1, 2, 4, 2, 4]` using a list method?
```python count_of_2 = nums.count(2) # 2 ```
31
Given `my_list = [10, 20, 30, 40]`, how do you replace a sublist `[20, 30]` with `[2, 3]` using slicing?
```python my_list[1:3] = [2, 3] # [10, 2, 3, 40] ```
32
How do you copy a list `nums = [1, 2, 3]` into `new_list` using a slice operation?
```python new_list = nums[:] ```
33
How do you copy a list `nums = [1, 2, 3]` into `new_list` using the built-in list method?
```python new_list = nums.copy() ```
34
Given `my_list = [1, 2, 3]`, how do you clear all its elements so that `my_list` becomes empty?
```python my_list.clear() ```
35
How do you convert a string "hello" into a list of characters `['h', 'e', 'l', 'l', 'o']`?
```python list_of_chars = list("hello") ```
36
How do you turn a list of characters `['p', 'y', 't', 'h', 'o', 'n']` into the string "python"?
```python word = "".join(['p', 'y', 't', 'h', 'o', 'n']) ```
37
How do you create a new list that contains tuples `(index, value)` for each element in `['a', 'b', 'c']` using `enumerate()`?
```python my_list = list(enumerate(["a", "b", "c"])) # [(0, 'a'), (1, 'b'), (2, 'c')] ```
38
How do you unpack the elements of `nums = [1, 2, 3]` into three variables `a, b, c` in Python?
```python a, b, c = nums ```
39
How do you use list slicing to split `nums = [1, 2, 3, 4, 5]` into `head = [1, 2, 3]` and `tail = [4, 5]`?
```python head = nums[:3] tail = nums[3:] ```
40
How do you multiply the list `[1, 2]` by 3 to get `[1, 2, 1, 2, 1, 2]`?
```python multiplied_list = [1, 2] * 3 ```
41
How do you flatten a list of lists `[[1, 2], [3, 4]]` into `[1, 2, 3, 4]` using a list comprehension?
```python flattened = [item for sublist in [[1, 2], [3, 4]] for item in sublist] ```
42
How do you slice a list `my_list = [0, 1, 2, 3, 4, 5]` to get `[2, 3, 4]`?
```python slice_part = my_list[2:5] # [2, 3, 4] ```
43
How do you remove duplicates from `nums = [1, 2, 2, 3, 3, 3]` while preserving order, using a list comprehension and a temporary set?
```python seen = set() unique_list = [x for x in nums if not (x in seen or seen.add(x))] # unique_list is [1, 2, 3] ```
44
How do you swap the first and last elements of `nums = [10, 20, 30, 40]` in a single line?
```python nums[0], nums[-1] = nums[-1], nums[0] ```
45
Given `nums = [1, 3, 5]`, how do you insert the value `2` at index `1` (so it becomes `[1, 2, 3, 5]`) using slicing?
```python nums[1:1] = [2] ```
46
How do you delete the second and third elements in `nums = [10, 20, 30, 40]` using slicing?
```python del nums[1:3] # Removes 20 and 30 ```
47
Given `nums = [4, 1, 3, 2]`, how do you sort it and store the sorted list in a new variable without modifying `nums`?
```python sorted_nums = sorted(nums) ```
48
How do you create a list with 5 zeros `[0, 0, 0, 0, 0]` using multiplication?
```python zeros = [0] * 5 ```
49
How do you count the total number of elements in `my_list = [5, 1, 2, 7]` using a built-in function?
```python length = len(my_list) # 4 ```
50
Given `letters = ["a", "b", "c", "d"]`, how do you print every element along with its index using a for loop?
```python for index, value in enumerate(letters): print(index, value) ```
51
How do you find the index of the last occurrence of `2` in `nums = [1, 2, 4, 2, 4]` by combining `index()` and slicing?
```python # Reverse the list, find index of first occurrence, and subtract from the length reverse_index = len(nums) - 1 - nums[::-1].index(2) # 3 ```
52
How do you use negative indexing to access the last element of a list `nums = [10, 20, 30]`?
```python nums[-1] # Returns 30 ```
53
Given `nums = [1, 2, 3, 4, 5]`, how do you slice from the second-to-last element to the end (`[4, 5]`) using negative indices?
```python slice_part = nums[-2:] # [4, 5] ```
54
How do you create a list from a range of numbers 0 to 4 using the `range()` function?
```python my_list = list(range(5)) # [0, 1, 2, 3, 4] ```
55
How do you use the `list` constructor to convert a tuple `(1, 2, 3)` into a list?
```python tuple_obj = (1, 2, 3) converted_list = list(tuple_obj) # [1, 2, 3] ```
56
How do you find whether all elements in `nums = [2, 4, 6]` are true (non-zero, non-empty) using a built-in function?
```python is_all_true = all(nums) # True, since 2, 4, and 6 are all non-zero ```
57
How do you find whether at least one element in `nums = [0, 0, 3]` is true using a built-in function?
```python is_any_true = any(nums) # True, because 3 is non-zero ```
58
How do you create a list of squares `[0, 1, 4, 9]` using `range(4)` and a list comprehension?
```python squares = [x*x for x in range(4)] ```
59
Given `nums = [1, 2, 3, 4]`, how do you create a new list containing only the elements greater than 2 using a list comprehension?
```python filtered = [x for x in nums if x > 2] # [3, 4] ```
60
How do you iterate over two lists `letters = ['a', 'b', 'c']` and `nums = [1, 2, 3]` at the same time using `zip()`?
```python for l, n in zip(letters, nums): print(l, n) ```
61
How do you reverse-iterate over a list `nums = [1, 2, 3]` using the built-in `reversed()` function in a for loop?
```python for val in reversed(nums): print(val) ```
62
How do you sort a list of strings `words = ["apple", "Banana", "cherry"]` by their lowercase forms (case-insensitive) using `sort()`?
```python words.sort(key=str.lower) ```
63
How do you slice a list `nums = [1, 2, 3, 4, 5]` to get the elements at odd indices (`[2, 4]`) using slicing with a step?
```python odd_indices = nums[1::2] ```
64
How do you destructively remove the elements at indices 0 through 2 (inclusive) from `nums = [1, 2, 3, 4, 5]` using slicing?
```python del nums[0:3] # nums becomes [4, 5] ```
65
How do you check if a list `nums = []` is empty by comparing its length to zero?
```python if len(nums) == 0: print("Empty") ```
66
Given `nums = [1, 2, 3]`, how do you create a shallow copy just by using the `list` constructor?
```python new_list = list(nums) ```
67
How do you replicate the list `[1, 2]` four times to create `[1, 2, 1, 2, 1, 2, 1, 2]`?
```python replicated = [1, 2] * 4 ```
68
How do you create a list of characters from the string `"python"` using a list comprehension (instead of `list("python")`)?
```python chars = [ch for ch in "python"] ```
69
Given `nums = [3, 2, 1]`, how do you sort it in ascending order without modifying the original list?
```python sorted_nums = sorted(nums) ```
70
How do you use a slice assignment to replace the last two elements of `nums = [10, 20, 30, 40]` with `[100, 200]`?
```python nums[-2:] = [100, 200] # nums becomes [10, 20, 100, 200] ```
71
Given `my_list = [1, 2, 3, 4]`, how do you check if the slice `[2, 3]` is in `my_list` as a contiguous sublist?
```python # There's no direct built-in, so you can check with a join trick for strings or manually: sub = [2, 3] found = any(my_list[i:i+len(sub)] == sub for i in range(len(my_list)-len(sub)+1)) ```
72
How do you handle attempting to remove an item with `list.remove(value)` if the value does not exist in the list (say `[1, 2, 3]` removing `5`) without throwing an error?
```python items = [1, 2, 3] val_to_remove = 5 if val_to_remove in items: items.remove(val_to_remove) ```
73
How do you flatten a nested list `[[1, 2], [3, 4], [5]]` using the built-in `sum` function trick?
```python nested = [[1, 2], [3, 4], [5]] flattened = sum(nested, []) # Not always recommended for large lists, but it works for simple cases ```
74
How do you remove the first occurrence of `"apple"` from `fruits = ["banana", "apple", "apple", "cherry"]` using a method call?
```python fruits.remove("apple") ```
75
Given `nums = [1, 2, 3, 4]`, how do you delete the element at index 2 without returning it?
```python del nums[2] ```
76
How do you add multiple elements `[3, 4, 5]` to the end of `nums = [1, 2]` in one operation without concatenation (`+`) or list comprehension?
```python nums.extend([3, 4, 5]) ```
77
How do you use the `map()` function to create a new list of absolute values from `nums = [-1, 2, -3]`?
```python abs_list = list(map(abs, nums)) # [1, 2, 3] ```
78
Given `letters = ['a', 'b', 'c']`, how do you prepend an element `'x'` at the very start using `insert()`?
```python letters.insert(0, 'x') # ['x', 'a', 'b', 'c'] ```
79
How do you convert a list of integers `[1, 2, 3]` into a single string `"123"` using `join()`?
```python nums = [1, 2, 3] combined = "".join(str(n) for n in nums) ```
80
How do you turn a dictionary's keys into a list given `d = {'a': 1, 'b': 2}`?
```python keys_list = list(d.keys()) # ['a', 'b'] ```
81
How do you unpack the list `nums = [1, 2, 3, 4]` into `a, b, *rest` where `rest` becomes `[3, 4]`?
```python a, b, *rest = nums ```
82
How do you create a list of tuples `[(1, 'a'), (2, 'b')]` from two lists `[1, 2]` and `['a', 'b']` using `zip()` and `list()`?
```python nums = [1, 2] chars = ['a', 'b'] combined = list(zip(nums, chars)) ```
83
How do you filter out `None` values from `data = [0, None, 1, None, 2]` using a list comprehension?
```python filtered = [x for x in data if x is not None] # [0, 1, 2] ```
84
How do you create a two-dimensional list (matrix) of zeros with 3 rows and 2 columns?
```python matrix = [[0]*2 for _ in range(3)] ```
85
How do you remove items from `nums = [1, 2, 3, 4, 5]` while iterating to only keep even numbers? (Hint: list comprehension)
```python nums = [x for x in nums if x % 2 == 0] ```
86
Given a list of words `['hello', 'world']`, how do you capitalize each word (first letter only) using a list comprehension?
```python capitalized = [w.capitalize() for w in ['hello', 'world']] ```
87
How do you get the index of the last element in a list `nums = [10, 20, 30]` without using `-1` or `len(nums)-1` directly?
```python last_index = len(nums) - 1 # last element is nums[last_index] ```
88
How do you create a list of the cumulative sums from `nums = [1, 2, 3]` (result `[1, 3, 6]`) using a simple for loop?
```python cumulative = [] running_total = 0 for n in nums: running_total += n cumulative.append(running_total) ```
89
How do you check if the sublist `[2, 3]` exists anywhere in `[1, 2, 3, 4, 5]` with a simple function (without fancy tricks)?
```python def contains_sublist(main_list, sublist): for i in range(len(main_list) - len(sublist) + 1): if main_list[i:i+len(sublist)] == sublist: return True return False result = contains_sublist([1, 2, 3, 4, 5], [2, 3]) # True ```
90
How do you shuffle the list `nums = [1, 2, 3, 4, 5]` in place using the `random` module (assuming it’s already imported)?
```python import random random.shuffle(nums) ```
91
How do you pick a random element from the list `colors = ["red", "blue", "green"]` using the `random` module?
```python import random choice = random.choice(colors) ```
92
How do you check if two lists `a = [1, 2, 3]` and `b = [1, 2, 3]` have the exact same elements in the same order using an operator?
```python a == b # True if both have the same content ```
93
How do you convert every element in `nums = [1, 2, 3]` to a string using the `map` function?
```python str_nums = list(map(str, nums)) # ['1', '2', '3'] ```
94
How do you check if all elements of `nums = [2, 4, 6]` are even in one line using a list comprehension and `all()`?
```python all_even = all(n % 2 == 0 for n in nums) ```
95
How do you join two lists `a = [1, 2]` and `b = [3, 4]` in-place so that `a` becomes `[1, 2, 3, 4]` without `+`?
```python a.extend(b) ```
96
How do you replicate a list `[0]` three times to get `[[0], [0], [0]]` but ensure each sublist is a separate object (not the same reference)?
```python separate_lists = [[0] for _ in range(3)] ```
97
How do you create a deep copy of a list of lists `[[1, 2], [3, 4]]` so changes in one do not affect the other, using the `copy` module?
```python import copy original = [[1, 2], [3, 4]] deep_copied = copy.deepcopy(original) ```
98
How do you find the index of the first occurrence of an element that satisfies a condition (e.g., value > 3) in `nums = [1, 3, 5, 7]`?
```python index = next(i for i, x in enumerate(nums) if x > 3) # index will be 2 (for value 5) ```
99
How do you find the index of the first occurrence of an element that satisfies a condition (e.g., value > 3) in `nums = [1, 3, 5, 7]`?
index = next(i for i, x in enumerate(nums) if x > 3) ## Footnote index will be 2 (for value 5)
100
How do you swap the elements at indices 1 and 2 in `nums = [10, 20, 30, 40]` in one line?
nums[1], nums[2] = nums[2], nums[1]
101
How do you multiply each element in `nums = [1, 2, 3]` by 3 using the `map()` function to produce `[3, 6, 9]`?
tripled = list(map(lambda x: x * 3, nums))
102
How do you split the list `nums = [1, 2, 3, 4, 5, 6]` into two parts at index 3 so that `left = [1, 2, 3]` and `right = [4, 5, 6]`?
left, right = nums[:3], nums[3:]
103
How do you slice a list `numbers = [10, 20, 30, 40, 50]` to get the sublist containing elements from index 2 up to (but not including) index 4?
sublist = numbers[2:4] # [30, 40]
104
How do you add the contents of `sublist = [7, 8]` to the front of `numbers = [1, 2, 3]` without creating a new list using `extend()`?
numbers[0:0] = sublist # numbers becomes [7, 8, 1, 2, 3]
105
Given `nums = [2, 4, 6]`, how do you insert an element `0` at the beginning of the list using slicing?
nums[:0] = [0] # nums becomes [0, 2, 4, 6]
106
How do you rotate the list `nums = [1, 2, 3, 4, 5]` by 2 positions to the left so it becomes `[3, 4, 5, 1, 2]` (using slicing)?
k = 2 nums = nums[k:] + nums[:k]
107
How do you rotate the list `nums = [1, 2, 3, 4, 5]` by 1 position to the right so it becomes `[5, 1, 2, 3, 4]`?
k = 1 nums = nums[-k:] + nums[:-k]
108
Given `nums = [3, 2, 5, 4, 1]`, how do you find the index of the maximum element using a one-line expression (without `max()` twice)?
max_index = nums.index(max(nums))
109
How do you sort a list of tuples `data = [(1, 'apple'), (3, 'cherry'), (2, 'banana')]` by the second element in each tuple, in ascending order?
data.sort(key=lambda x: x[1]) # data becomes [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
110
How do you use the `bisect` module to insert `15` into a sorted list `nums = [2, 5, 10, 20]` while maintaining sorted order?
import bisect bisect.insort(nums, 15) # nums becomes [2, 5, 10, 15, 20]
111
How do you use `bisect_left()` to find the position of `10` in `nums = [2, 5, 10, 20]` (assuming it’s sorted)?
import bisect pos = bisect.bisect_left(nums, 10) # pos is 2
112
How do you check if two lists `a` and `b` refer to the same object in memory (not just have the same contents)?
if a is b: print("They reference the same object")
113
How do you do an element-wise addition of two lists `a = [1, 2, 3]` and `b = [4, 5, 6]` to get `[5, 7, 9]` using a list comprehension?
result = [x + y for x, y in zip(a, b)] # [5, 7, 9]
114
Given `nums = [1, 2, 2, 3, 2]`, how do you find all the indices where `2` appears, using a list comprehension?
indices_of_2 = [i for i, val in enumerate(nums) if val == 2] # [1, 2, 4]
115
How do you join a list of strings `words = ["Python", "is", "fun"]` into a single string with spaces "Python is fun"?
sentence = " ".join(words)
116
How do you remove an element at index 3 in `nums = [0, 1, 2, 3, 4, 5]` only if that index exists, without causing an error?
if len(nums) > 3: del nums[3]
117
How do you create a list of even numbers from 0 to 8 using `range()` and the `list` constructor?
evens = list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
118
How do you add three copies of `['A', 'B']` to an empty list so that each copy is a separate object (hint: use a loop or list comprehension)?
separate_copies = [['A', 'B'] for _ in range(3)]
119
How do you ensure you create a 2D list of zeros sized 2x3 (2 rows, 3 columns) without referencing the same row object repeatedly?
rows = 2 cols = 3 matrix = [[0] * cols for _ in range(rows)]
120
Given `nums = [1, 2, 3, 4, 5]`, how do you reverse it and iterate over it at the same time in a `for` loop, without modifying `nums`?
for val in reversed(nums): print(val)
121
How do you get a list of all possible pairs `(x, y)` from `nums = [1, 2]` and `letters = ['a', 'b']` using a nested list comprehension?
pairs = [(x, y) for x in nums for y in letters] # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
122
Given `nums = [10, 20, 30]`, how do you delete the *entire* list so that its name is no longer defined?
del nums # nums no longer exists
123
How do you make `copied = original.copy()` while keeping in mind that it’s only a shallow copy (nested structures still reference the same objects)?
copied = original.copy() # This is shallow; for a deep copy, use copy.deepcopy(original)
124
How do you find and remove every occurrence of `2` in the list `nums = [1, 2, 3, 2, 4, 2]` using a comprehension?
nums = [x for x in nums if x != 2] # Now nums no longer contains 2
125
How do you check if the list `nums = [1, 2, 3]` is strictly increasing (each element is larger than the previous) in a single line?
is_increasing = all(nums[i] < nums[i+1] for i in range(len(nums)-1))
126
Given `nums = [1, 3, 5, 7]`, how do you insert `2` at the appropriate place to keep `nums` sorted without writing custom logic? (Hint: `bisect.insort()`)
import bisect bisect.insort(nums, 2) # nums becomes [1, 2, 3, 5, 7]
127
How do you find if a list `nums = [4, 4, 4]` has all identical elements in one line?
all_identical = len(set(nums)) == 1
128
How do you find if a list `nums = [10, 20, 30]` is already in ascending order without manually looping?
is_sorted = nums == sorted(nums)
129
How do you keep only the first 3 elements in `nums = [1, 2, 3, 4, 5, 6]`, removing the rest in-place with slicing?
nums[3:] = [] # nums becomes [1, 2, 3]
130
How do you insert multiple values `[100, 200]` at index 2 of `nums = [0, 1, 2, 3]` using slicing?
nums[2:2] = [100, 200] # nums becomes [0, 1, 100, 200, 2, 3]
131
How do you create a list that contains the lengths of each sublist in `nested = [[1, 2], [3, 4, 5], [], [6]]` using a list comprehension?
lengths = [len(sublist) for sublist in nested] # [2, 3, 0, 1]
132
How do you generate a list of random integers between 1 and 10 (inclusive) of length 5 using the `random` module (assuming it’s imported)?
import random rand_list = [random.randint(1, 10) for _ in range(5)]
133
How do you remove an element by value (`'banana'`) from `fruits = ["apple", "banana", "cherry"]`, but only if it exists, using a try-except block?
try: fruits.remove("banana") except ValueError: pass # Do nothing if "banana" isn't in the list
134
How do you remove the first three elements from `nums = [1, 2, 3, 4, 5]` in-place with `del` and slicing?
del nums[:3] # nums becomes [4, 5]
135
Given two lists of the same length, `a = [1, 2, 3]` and `b = [4, 5, 6]`, how do you merge them into a list of tuples `[(1,4), (2,5), (3,6)]`?
merged = list(zip(a, b))
136
How do you create a new list of booleans from `nums = [1, 2, 3, 4]` where each element indicates if the corresponding original value is even (`True` if even)?
is_even_list = [x % 2 == 0 for x in nums] # [False, True, False, True]
137
How do you compute the cumulative product of `nums = [1, 2, 3, 4]` (result `[1, 2, 6, 24]`) using a simple loop?
cumulative = [] current_product = 1 for n in nums: current_product *= n cumulative.append(current_product)
138
How do you convert a list of numeric strings `['10', '20', '30']` into a list of integers `[10, 20, 30]` using a list comprehension?
nums = [int(x) for x in ["10", "20", "30"]]
139
How do you check whether any element in `nums = [1, 2, 3]` is greater than 2 using `any()`?
condition = any(n > 2 for n in nums) # True
140
How do you create all permutations of length 2 from the list `[1, 2, 3]` using `itertools.permutations`?
import itertools perms = list(itertools.permutations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
141
How do you create a list of prime numbers under 20 using a simple list comprehension and a helper function `is_prime(n)`?
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True primes_under_20 = [x for x in range(20) if is_prime(x)]
142
Given `nums = [1, 2, 3, 4, 5]`, how do you split it into chunks of size 2, producing `[[1, 2], [3, 4], [5]]`?
def chunk_list(lst, size): return [lst[i:i+size] for i in range(0, len(lst), size)] chunks = chunk_list(nums, 2)
143
How do you make a shallow copy of `nums = [1, 2, 3]` simply by using the `*` (splat) operator in a list literal?
copy_of_nums = [*nums]
144
How do you insert `'x'` between every character of the string `"abc"` using a list comprehension, resulting in `['a', 'x', 'b', 'x', 'c']`?
s = "abc" with_x = [elem for pair in zip(s, "x") for elem in pair] + [s[-1]]
145
How do you create a copy of the list `nums = [1, 2, 3]` using the `*` (splat) operator?
```python copy_of_nums = [*nums] ```
146
How do you insert `'x'` between every character of the string `"abc"` using a list comprehension?
```python s = "abc" with_x = [elem for pair in zip(s, "x"*(len(s)-1)) for elem in pair] + [s[-1]] # or simpler: list("x".join(s)) if you don't mind splitting afterwards ``` ## Footnote The alternative approach: `list("x".join("abc"))` gives `['a', 'x', 'b', 'x', 'c']`.
147
How do you get the Cartesian product of `[1, 2]` and `['a', 'b']` using `itertools.product()`?
```python import itertools product_list = list(itertools.product([1, 2], ['a', 'b'])) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] ```
148
How do you slice a list `my_list = [1, 2, 3, 4, 5, 6]` to get every third element?
```python result = my_list[0::3] ```
149
How do you find the most frequent element in `nums = [2, 3, 2, 5, 2, 3]` using `max()` with a custom key?
```python most_frequent = max(nums, key=nums.count) # 2 ```
150
How do you split a string `"one,two,three"` on commas into a list using a built-in string method?
```python s = "one,two,three" parts = s.split(",") # ["one", "two", "three"] ```
151
How do you transform the list `['hello', 'world']` into `['HELLO', 'WORLD']` using the `upper()` method and a list comprehension?
```python words = ["hello", "world"] upper_words = [w.upper() for w in words] ```
152
How do you use `itertools.chain` to flatten a list of lists, `nested = [[1, 2], [3, 4], [5]]`?
```python import itertools flattened = list(itertools.chain.from_iterable(nested)) # [1, 2, 3, 4, 5] ```
153
How do you find the index of the second occurrence of `3` in `[1, 3, 5, 3, 7]` using a small helper trick with `enumerate()`?
```python vals = [1, 3, 5, 3, 7] positions = [i for i, x in enumerate(vals) if x == 3] second_index = positions[1] # 3 ```
154
How do you create a list of length 5 where each element is a random boolean (`True` or `False`) using `random.choice()`?
```python import random bool_list = [random.choice([True, False]) for _ in range(5)] ```
155
How do you remove elements at even indices from the list `nums = [0, 1, 2, 3, 4, 5]` in one line, leaving only the elements at odd indices (`[1, 3, 5]`)?
```python nums = [nums[i] for i in range(len(nums)) if i % 2 == 1] ```
156
Given `nums = [1, 2, 3, 4, 5]`, how do you create a new list where each value is paired with its index, resulting in `[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]`?
```python indexed_list = list(enumerate(nums)) ```
157
How do you combine two lists element-wise with a function? For example, add each pair of elements in `a = [1, 2]` and `b = [10, 20]` to get `[11, 22]` using `map()` and `lambda`?
```python a = [1, 2] b = [10, 20] combined = list(map(lambda x, y: x + y, a, b)) # [11, 22] ```
158
How do you convert a list of single-character strings `['p', 'y', 't', 'h', 'o', 'n']` to uppercase (`['P', 'Y', 'T', 'H', 'O', 'N']`) using a list comprehension?
```python chars = ['p', 'y', 't', 'h', 'o', 'n'] upper_chars = [c.upper() for c in chars] ```
159
How do you generate a list of prime numbers between 1 and 30 (inclusive) using a one-line list comprehension and a helper `is_prime` function?
```python def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True primes_1_to_30 = [x for x in range(1, 31) if is_prime(x)] ```
160
How do you multiply corresponding elements of two lists `a = [1, 2, 3]` and `b = [4, 5, 6]` to get `[4, 10, 18]` using a list comprehension?
```python product_list = [x*y for x, y in zip(a, b)] ```
161
Given a list of mixed data types `items = [1, 'two', 3.0, None, True]`, how do you filter out only the integers (`[1]`) using `isinstance()` in a comprehension?
```python ints_only = [x for x in items if isinstance(x, int)] ```
162
How do you remove every second element from `nums = [10, 20, 30, 40, 50]` (keeping `[10, 30, 50]`) by using slicing?
```python nums = nums[0::2] ```
163
How do you sum corresponding elements of `[[1, 2], [3, 4], [5, 6]]` to get `[9, 12]` (summing vertically) using `zip()`?
```python lists = [[1, 2], [3, 4], [5, 6]] summed = [sum(x) for x in zip(*lists)] # [9, 12] ```
164
How do you insert `['alpha', 'beta']` at the very beginning of `words = ['gamma', 'delta']` using slicing?
```python words[:0] = ['alpha', 'beta'] ```
165
How do you remove elements from index 2 up to (but not including) 5 in `nums = [0, 1, 2, 3, 4, 5, 6]` using the `del` statement?
```python del nums[2:5] # nums becomes [0, 1, 5, 6] ```
166
How do you reverse the order of strings in the list `words = ['one', 'two', 'three']` by using `[:: -1]` slicing, without changing the original?
```python reversed_words = words[::-1] ```
167
How do you keep only unique elements from the list `[1, 2, 1, 3, 2]` while preserving the original order, using a loop and a helper set?
```python seen = set() unique_list = [] for x in [1, 2, 1, 3, 2]: if x not in seen: unique_list.append(x) seen.add(x) ```
168
Given `nums = [1, 2, 3, 4, 5]`, how do you slice it to get every element except the first and last (`[2, 3, 4]`)?
```python middle = nums[1:-1] ```
169
How do you fill a list of length 5 with the same random integer between 1 and 10 for each element? (Hint: generate once, then multiply.)
```python import random value = random.randint(1, 10) filled_list = [value] * 5 ```
170
How do you create a list of 10 random integers between 0 and 50, but each integer is distinct? (Hint: use `random.sample()`.)
```python import random distinct_randoms = random.sample(range(51), 10) ```
171
How do you extract just the second elements of each tuple from `pairs = [(0, 'a'), (1, 'b'), (2, 'c')]` to get `['a', 'b', 'c']`?
```python second_elements = [y for (x, y) in pairs] ```
172
How do you convert a list of integers `[3, 4, 5]` to a list of floats `[3.0, 4.0, 5.0]` using a list comprehension?
```python floats = [float(x) for x in [3, 4, 5]] ```
173
How do you discard the first 2 elements and the last 2 elements of `nums = [10, 20, 30, 40, 50, 60]`, leaving `[30, 40]`?
```python nums = nums[2:-2] ```
174
How do you confirm that a list `nums = [10, 20, 30]` is the same object as another reference `alias_of_nums = nums` (not just equal in value)?
```python nums is alias_of_nums ```
175
How do you turn a list of booleans `[True, False, True]` into their integer equivalents `[1, 0, 1]` using `map()`?
```python bools = [True, False, True] int_bools = list(map(int, bools)) ```
176
How do you generate a list of all 2-combinations from `[1, 2, 3]` using `itertools.combinations`?
```python import itertools combos = list(itertools.combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)] ```
177
How do you find the intersection of two lists, `a = [1, 2, 3]` and `b = [2, 3, 4]`, in a single line (order does not matter)?
```python intersection = list(set(a) & set(b)) # [2, 3] (order may vary) ```
178
How do you find the difference of two lists, `a = [1, 2, 3, 3]` and `b = [2, 4]`, so you get elements in `a` that are not in `b` (with duplicates preserved)?
```python result = a[:] for x in b: if x in result: result.remove(x) # result becomes [1, 3, 3] ```
179
How do you slice a list `nums = [1, 2, 3, 4, 5, 6]` so that you keep just `[2, 3, 4]` by removing 1 element from the start and 2 from the end?
```python nums = nums[1:-2] ```
180
How do you append the list `[100, 200]` as a single item to `nums = [10, 20]` (resulting in `[10, 20, [100, 200]]`) using a built-in method?
```python nums.append([100, 200]) ```
181
How do you copy elements from index `start` to index `end` (not including `end`) of `nums` into a new list using slicing (assuming you have these variables defined)?
```python slice_copy = nums[start:end] ```
182
How do you check if a list `nums` contains any duplicates by using a simple set comparison (`len`) trick?
```python has_duplicates = len(nums) != len(set(nums)) ```
183
How do you create a list of length 10, where each element is `'hello'`, without repeating the same object reference if it were mutable?
```python repeated_strings = ['hello' for _ in range(10)] ```
184
How do you count how many integers in `nums = [1, 2, 'x', 3, 'y']` are actually integers?
```python count_integers = sum(1 for x in nums if isinstance(x, int)) ```
185
How do you add a large range of elements (from 10 to 14) at the end of `nums = [0, 1, 2]` using `extend()` and `range()`?
```python nums.extend(range(10, 15)) # [0, 1, 2, 10, 11, 12, 13, 14] ```
186
How do you transform `nums = [1, 2, 3]` into a list of dictionaries `[{'val': 1}, {'val': 2}, {'val': 3}]` using a comprehension?
```python dicts = [{'val': x} for x in nums] ```
187
How do you use slicing to replace the elements at indices 1 through 3 of `nums = [0, 1, 2, 3, 4, 5]` with `[9, 9]`?
```python nums[1:4] = [9, 9] # nums becomes [0, 9, 9, 4, 5] ```
188
Given `names = ['Alice', 'Bob', 'Charlie']`, how do you extract just the first letters of each name to get `['A', 'B', 'C']` with a list comprehension?
```python first_letters = [name[0] for name in names] ```
189
How do you find the cumulative minimum of `nums = [5, 2, 7, 1, 1, 8]` (e.g., `[5, 2, 2, 1, 1, 1]`) using a loop?
```python cumulative_min = [] current_min = float('inf') for n in nums: if n < current_min: current_min = n cumulative_min.append(current_min) ```
190
How do you generate a list of squares of numbers from 1 to 5, but skip squaring the number 3, using a list comprehension?
```python squares_skip_3 = [x*x for x in range(1, 6) if x != 3] ```
191
How do you find the position of the first element in `nums = [1, -1, 2, -2, 3]` that’s negative, using a generator expression and `next()`?
```python index_of_first_negative = next(i for i, x in enumerate(nums) if x < 0) # Returns 1 for value -1 ```
192
How do you remove all the negative numbers from `nums = [2, -1, 3, -5, 4]` in-place without creating a new list? (Hint: iterate backward or slice-assign)
```python i = 0 while i < len(nums): if nums[i] < 0: del nums[i] else: i += 1 ```
193
How do you merge and sort two pre-sorted lists `a = [1, 3, 5]` and `b = [2, 4, 6]` without using `sorted(a + b)`? (Hint: the `heapq.merge()` approach)
```python import heapq merged_sorted = list(heapq.merge(a, b)) # [1, 2, 3, 4, 5, 6] ```
194
How do you retrieve the third item from the end in the list `nums = [10, 20, 30, 40, 50]` using negative indexing?
```python item = nums[-3] # 30 ```
195
How do you create a list of the factorial values for 1 through 5 using `math.factorial` in a list comprehension?
```python import math factorials = [math.factorial(x) for x in range(1, 6)] ```
196
How do you create a list of the factorial values for 1 through 5 using `math.factorial` in a list comprehension?
```python import math factorials = [math.factorial(x) for x in range(1, 6)] # [1, 2, 6, 24, 120] ```
197
How do you chunk `nums = [1, 2, 3, 4, 5, 6]` into pairs using `zip()` so that you get `[(1,2), (3,4), (5,6)]`?
```python chunked = list(zip(nums[0::2], nums[1::2])) # [(1, 2), (3, 4), (5, 6)] ```
198
How do you extract only the digits from a mixed list `items = ["abc", 123, "45", None, 6]` and convert them to integers, resulting in `[123, 45, 6]`?
```python extracted = [] for item in items: if isinstance(item, int): extracted.append(item) elif isinstance(item, str) and item.isdigit(): extracted.append(int(item)) ```
199
How do you compute the running average of `nums = [2, 4, 6, 8]`, producing `[2.0, 3.0, 4.0, 5.0]` using a loop?
```python running_avg = [] total = 0 for i, x in enumerate(nums, start=1): total += x running_avg.append(total / i) ```
200
How do you generate a list of random floats between 0 and 1 of length 5 using `random.random()` in a list comprehension?
```python import random random_floats = [random.random() for _ in range(5)] ```
201
How do you count how many sublists in `nested = [[1], [2, 3], [], [4, 5, 6]]` have length greater than 1 using a comprehension?
```python count_sub_more_than_one = sum(1 for sub in nested if len(sub) > 1) ```
202
Given `matrix = [[1, 2, 3], [4, 5, 6]]`, how do you transpose it to get `[[1, 4], [2, 5], [3, 6]]` using `zip()`?
```python transposed = list(map(list, zip(*matrix))) ```
203
How do you convert a list of booleans `[True, False, True]` to the string `"101"` (concatenating '1' for True and '0' for False)?
```python bools = [True, False, True] binary_str = "".join('1' if b else '0' for b in bools) ```
204
How do you print each element of `nums = [1, 2, 3]` on the same line, separated by a space, using `print(*nums)` in Python?
```python print(*nums) # Outputs: 1 2 3 ```
205
How do you remove the element at index 1 in `nums = [10, 20, 30]` and insert the string `"twenty"` at the same position (two operations)?
```python del nums[1] nums.insert(1, "twenty") # nums becomes [10, "twenty", 30] ```