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