60 Python List Questions Flashcards
Check if a list contains an element
The in membership operator will return True if a specific element is in the list
li = [1,2,3,’a’,’b’,’c’]
‘a’ in li # True
How to iterate over 2+ lists at the same time
You can zip() lists and then iterate over the zip obj. A zip obj is an iterator of tuples
name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff'] animal = ['Cat', 'Dog','Fish', 'Goat'] age = [1,2,2,6]
z = zip(name, animal, age)
for name, animal, age in z:
print(“%s the %s is %s” % (name, animal, age))
Snowball the Cat is 1 Chewy the Dog is 2 Bubbles the Fish is 2 Gruff the Goat is 6
When would you use a list vs dictionary?
Depends on use-case, dictionary searches are faster than lists
Use list when order matters
ids = [23,1,7,9]
Use dictionary when you want to tally occurances
pets = {‘dogs’: 2, ‘cats’: 1, ‘fish’: 5}
Is a list mutable?
Yes, notice same memory address
x = [1]
print(id(x), ‘:’, x) # 2769545838976 : [1]
x.append(5)
x.extend([6,7])
print(id(x), ‘:’, x) # 2769545838976 : [1, 5, 6, 7, 5, 6, 7]
Does a list need to be homogeneous?
Nope, different types of objects can be mixed together in a list
a = [1, ‘a’, 1.0, []]
a # [1, ‘a’, 1.0, []]
What’s the difference between append and extend?
.append() adds a single obj to the end of a list
a = [1,2,3]
a.append(4)
a # [1,2,3,4]
.extend() combines their values
b = [1,2,3]
b.extend([5,6])
b #=> [1, 2, 3, 5, 6] # [1, 2, 3, 5, 6]
Do Python lists store values or pointers?
Lists are mutable they store pointers than actual values in memory
print(id(1)) # 140718920247088
print(id(2)) # 140718920247120
a = [1,2,3]
print(id(a)) # 2769551452544
print(id(a[0])) # 140718920247088
print(id(a[1])) # 140718920247120
What does ‘del’ do?
del removes an item from a list given its index
a = [‘w’, ‘x’, ‘y’, ‘z’]
a #=> [‘w’, ‘x’, ‘y’, ‘z’]
del a[1]
a #=> [‘w’, ‘y’, ‘z’]
What is the difference between ‘remove’ and ‘pop’?
.remove() removes the first instance of a matching obj
a = [‘a’, ‘a’, ‘b’, ‘b’, ‘c’, ‘c’]
a.remove(‘b’)
a # [‘a’, ‘a’, ‘b’, ‘c’, ‘c’]
pop() removes the last element of a list by default if an index isn’t specified pop(2)
a = [‘a’, ‘a’, ‘b’, ‘b’, ‘c’, ‘c’]
a.pop(4) #=> ‘c’
Remove duplicates from a list
If you’re not concerned about maintaining the order of a list, then convert to a set then back to a list
li = [3, 2, 2, 1, 1, 1]
list(set(li)) # [1, 2, 3]
Find the idx of the 1st matching element
Use index() to search by value and return the index
fruit = [‘pear’, ‘orange’, ‘apple’, ‘grapefruit’, ‘apple’, ‘pear’]
fruit. index(‘apple’) # 2
fruit. index(‘pear’) # 0
Remove all elements from a list
Rather than creating a new empty list, we can clear the elements from list with .clear() or del fruit[:]
fruit = [‘pear’, ‘orange’, ‘apple’]
print( fruit ) # [‘pear’, ‘orange’, ‘apple’]
print( id(fruit) ) #4581174216
fruit.clear()
print( fruit ) # []
print( id(fruit) ) # 4581174216
Iterate over both the values in a list and their indices
enumerate() adds a counter to the list passed as an argument
grocery_list = [‘flour’,’cheese’,’carrots’]
for idx,val in enumerate(grocery_list):
print(“%s: %s” % (idx, val))
0: flour # 1: cheese # 2: carrots
How to concatenate two list
the + operator will concatenate 2 lists
one = ['a', 'b', 'c'] two = [1, 2, 3]
one + two # [‘a’, ‘b’, ‘c’, 1, 2, 3]
How to manipulate every element in a list with list comprehension
Below return a new list with 1 added to every element
li = [0, 25, 50, 100]
[i+1 for i in li] # [1, 26, 51, 101]
Count the occurrence of a specific object in a list
The count() returne the number of occurrences of a specific object
pets = [‘dog’,’cat’,’fish’,’fish’,’cat’]
pets.count(‘fish’) # 2
How to shallow copy a list?
.copy() can be used to shallow copy a list
round1 = [‘chuck norris’, ‘bruce lee’, ‘sonny chiba’]
round2 = round1.copy()
round2.remove(‘sonny chiba’)
print(round1) #[‘chuck norris’, ‘bruce lee’, ‘sonny chiba’]
print(round2)# [‘chuck norris’, ‘bruce lee’]
Why create a shallow copy of a list?
round1 = [‘chuck norris’, ‘bruce lee’, ‘sonny chiba’]
round2 = round1
round2.remove(‘sonny chiba’)
print(round1) # [‘chuck norris’, ‘bruce lee’]
print(round2) # [‘chuck norris’, ‘bruce lee’]
Without a shallow copy, round1 and round2 are just names pointing to the same list in memory.
How to deep copy a list?
For this we need to import the copy module, then call copy.deepcopy().
Below we create a deep copy of a list, round1 called round2, update a value in round2, then print both. In this case, round1 isn’t affected.
round1 = [[‘Arnold’, ‘Sylvester’, ‘Jean Claude’], [‘Buttercup’, ‘Bubbles’, ‘Blossom’] ]
import copy
round2 = copy.deepcopy(round1)round2[0][0] = ‘Jet Lee’
What is the difference bewtween a deep copy and a shallow copy?
Creating a shallow copy does create a new object in memory, but it’s filled with the same references to existing objects that the previous list has.
Creating a deep copy creates copies of the original objects and points to these new versions. So the new list is completely unaffected by changes to the old list and vice versa.
What is the difference between a list and a tuple?
Tuples cannot be updated after creation. Adding/removing/updating an existing tuple requires creating a new tuple.
Lists can be modified after creation.
Tuples often represent an object like a record loaded from a database where elements are of different datatypes.
Lists are generally used to store an ordered sequence of a specific type of object (but not always).
Both are sequences and allow duplicate values.
Return the length of a list
len() can return the length of a list
li = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
len(li) #5
But note it counts top level objects, so a nested list of several integers will only be counted as a single object. Below, li has a length of 2, not 5.
li = [[1,2],[3,4,5]]
len(li) #2
What is the difference between a list and a set?
While a list is ordered, a set is not. That’s why using set to find unique values in a list, like list( set([3, 3, 2, 1]) ) loses the order.
While lists are often used to track order, sets are often used to track existence.
Lists allow duplicates, but all values in a set are unique by definition.
How to check if an element is not in a list?
For this we use the in membership operator, but prefix with not.
li = [1,2,3,4]
5 not in li # True
4 not in li # False
Multiply every element in a list by 5 with the map function
.map() allows iterating over a sequence and updating each value with another function.
def multiply\_5(val): return val \* 5
a = [10,20,30,40,50]
[val for val in map(multiply_5, a)] # [50, 100, 150, 200, 250]
Combine 2 lists into a list of tuple with the zip function
zip() combines multiple sequences into an iterator of tuples, where values at the same sequence index are combined in the same tuple.
alphabet = [‘a’, ‘b’, ‘c’] integers = [1, 2, 3]
list(zip(alphabet, integers)) # [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Insert a value at a specific index in an existing list
The insert() method takes an object to insert and the index to insert it at.
li = [‘a’,’b’,’c’,’d’,’e’]
li.insert(2, ‘HERE’)
li # [‘a’, ‘b’, ‘HERE’, ‘c’, ‘d’, ‘e’]
Subtract values in a list from the first element with the reduce function
reduce() needs to be imported from functools.
Given a function, reduce iterates over a sequence and calls the function on every element. The output from the previous element is passed as an argument when calling the function on the next element.
from functools import reduce
def subtract(a,b):
return a - b
numbers = [100,10,5,1,2,7,5]
reduce(subtract, numbers) # 70
Remove negative values from a list with the filter function
Given a function, filter() will remove any elements from a sequence on which the function doesn’t return True.
Below we remove elements less than zero.
def remove\_negatives(x): return True if x \>= 0 else False
a = [-10, 27, 1000, -1, 0, -30]
[x for x in filter(remove_negatives, a)] # [27, 1000, 0]
Convert a list into a dictionary where list elements are keys
For this we can use a dictionary comprehension
li = [‘The’, ‘quick’, ‘brown’, ‘fox’, ‘was’, ‘quick’]
d = {k:1 for k in li}
d #=> {‘The’: 1, ‘quick’: 1, ‘brown’: 1, ‘fox’: 1, ‘was’: 1}
Modify an existing list with a lambda function
Let’s take the previous map function we wrote and turn it into a one-liner with a lambda.
a = [10,20,30,40,50]
list(map(lambda val:val*5, a)) # [50, 100, 150, 200, 250]
Remove elements in a list after a specific index
Using the slice syntax, we can return a new list with only the elements up to a specific index.
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[:10] # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Remove elements in a list before a specific index
The slice syntax can also return a new list with the values after a specified index.
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[15:] # [16, 17, 18, 19, 10]
Remove elements in a list between 2 indices
Or between two indices
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[12:17] # [13, 14, 15, 16, 17]
Return every 2nd element in a list between 2 indices
Or before/after/between indices at a specific interval.
Here we return every 2nd value between the indices 10 and 16 using the slice syntax.
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[10:16:2] # [11, 13, 15]
Sort a list of integers in ascending order
The sort() method mutates a list into ascending order.
li = [10,1,9,2,8,3,7,4,6,5]
li.sort()
li # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sort a list of integers in descending order
It’s also possible to sort in descending order with sort() by adding the argument reverse=True.
li = [10,1,9,2,8,3,7,4,6,5]
li.sort(reverse=True)
li # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Filter even values out of a list with list comprehension
You can add conditional logic inside a list comprehension to filter out values following a given pattern.
Here we filter out values divisible by 2.
li = [1,2,3,4,5,6,7,8,9,10]
[i for i in li if i % 2 != 0] # [1, 3, 5, 7, 9]
Count occurrences of each value in a list
One option is to iterate over a list and add counts to a dictionary. But the easiest option is to import the Counter class from collections and pass the list to it.
from collections import Counter
li = [‘blue’, ‘pink’, ‘green’, ‘green’, ‘yellow’, ‘pink’, ‘orange’]
Counter(li) # Counter({‘blue’: 1, ‘pink’: 2, ‘green’: 2, ‘yellow’: 1, ‘orange’: 1})
Get the first element from each nested list in a list
A list comprehension is well suited for iterating over a list of other objects and grabbing an element from each nested object.
li = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
[i[0] for i in li] # [1, 4, 7, 10, 13]
What is the time complexity of insert, find and delete for a list?
Insert is O(n). If an element is inserted at the beginning, all other elements must be shifted right.
Find by index is O(1). But find by value is O(n) because elements need to be iterated over until the value is found.
Delete is O(n). If an element is deleted at the beginning, all other elements must to be shifted left.
Combine elements in a list into a single string
This can be done with the join() function
li = [‘The’,’quick’,’brown’, ‘fox’, ‘jumped’, ‘over’, ‘the’, ‘lazy’, ‘dog’]
“ “.join(li) # ‘The quick brown fox jumped over the lazy dog’
What’s the affect of multiplying a list by an integer?
Multiplying a list by an integer is called multiple concatenation and has the same affect as concatenating a list to itself n-times.
[‘a’,’b’] * 5 # [‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’]
Use the “any” function to return True if any value in a list is divisible by 2
We can combine any() with a list comprehension to return True if any values in the returned list evaluate to True.
Below the 1st list comprehension returns True because the list has a 2 in it, which is divisible by 2.
li1 = [1,2,3] li2 = [1,3]
any(i % 2 == 0 for i in li1) # True
any(i % 2 == 0 for i in li2) # False
Use the “all” function to return True if all values in a list are negative
Similar to the any() function, all() can also be used with a list comprehension to return True only if all values in the returned list are True.
li1 = [2,3,4] li2 = [2,4]
all(i % 2 == 0 for i in li1) # False
all(i % 2 == 0 for i in li2) # True
Can you sort a list with “None” in it?
You cannot sort a list with None in it because comparison operators (used by sort()) can’t compare an integer with None.
li = [10,1,9,2,8,3,7,4,6,None]
li.sort()
li # TypeError: ‘
What kind of copy would the list constructor create from an existing list?
The list constructor creates a shallow copy of a passed in list. That said, this is less pythonic than using .copy().
li1 = [‘a’,’b’]
li2 = list(li1)
li2.append(‘c’)
print(li1) # [‘a’, ‘b’]
print(li2) # [‘a’, ‘b’, ‘c’]
Reverse the order of a list
A list can be mutated into reverse order with the reverse() method.
li = [1,2,3,4,5,6,7,8,9,10]
li.reverse() # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
What is the difference between reverse and reversed?
reverse() reverses the list in place. reversed() returns an iterable of the list in reverse order.
li = [1,2,3,4,5,6,7,8,9,10]
list(reversed(li)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
What is the difference between sort and sorted?
sort() modifies the list in place. sorted() returns a new list in reverse order.
li = [10,1,9,2,8,3,7,4,6,5]
li.sort()
li # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
li = [10,1,9,2,8,3,7,4,6,5]
sorted(li) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Return the minimum value in a list
The min() function returns the minimum value in a list.
li = [10,1,9,2,8,3,7,4,6,5]
min(li) # 1
Return the maximum value in a list
The max() function returns the maximum value in a list.
li = [10,1,9,2,8,3,7,4,6,5]
max(li) # 10
Return the sum of values in a list
The sum() function returns the sum of all values in a list.
li = [10,1,9,2,8,3,7,4,6,5]
sum(li) # 55
Use a list as a stack
You can use append() and pop() to treat a list like a stack. Stacks function per LIFO (last in first out).
stack = []
stack. append(‘Jess’)
stack. append(‘Todd’)
stack. append(‘Yuan’)
print(stack) # [‘Jess’, ‘Todd’, ‘Yuan’]
print(stack.pop()) # Yuan
print(stack) # [‘Jess’, ‘Todd’]
Find the intersection of 2 lists
We can do this by utilizing set() with an ampersand.
li1 = [1,2,3] li2 = [2,3,4]
set(li1) & set(li2) # {2, 3}
Find the difference between a set and another set
We can’t subtract lists, but we can subtract sets.
li1 = [1,2,3]
li2 = [2,3,4]
set(li1) - set(li2) #{1}
set(li2) - set(li1) #{4}
Flatten a list of lists with a list comprehensions
Unlike Ruby, Python3 doesn’t have an explicit flatten function. But we can use list comprehension to flatten a list of lists.
li = [[1,2,3],[4,5,6]]
[i for x in li for i in x] # [1, 2, 3, 4, 5, 6]
Generate a list of every integer between 2 values
We can create a range between 2 values and then convert that to a list.
list(range(5,10)) # [5, 6, 7, 8, 9]
Combine two lists into a dictionary
Using zip() and the list() constructor we can combine 2 lists into a dictionary where one list becomes the keys and the other list becomes the values.
name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff'] animal = ['Cat', 'Dog', 'Fish', 'Goat']
dict(zip(name, animal)) # {‘Snowball’: ‘Cat’, ‘Chewy’: ‘Dog’, ‘Bubbles’: ‘Fish’, ‘Gruff’: ‘Goat’}
Reverse the order of a list using the slice syntax
While we can reverse a list with reverse() and reversed(), it can also be done with the slice syntax.
li = [‘a’,’b’,3,4]
li[::-1] # [4, 3, ‘b’, ‘a’]