60 Python List Questions Flashcards

1
Q

Check if a list contains an element

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to iterate over 2+ lists at the same time

A

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

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

When would you use a list vs dictionary?

A

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}

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

Is a list mutable?

A

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]

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

Does a list need to be homogeneous?

A

Nope, different types of objects can be mixed together in a list

a = [1, ‘a’, 1.0, []]
a # [1, ‘a’, 1.0, []]

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

What’s the difference between append and extend?

A

.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]

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

Do Python lists store values or pointers?

A

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

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

What does ‘del’ do?

A

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’]

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

What is the difference between ‘remove’ and ‘pop’?

A

.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’

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

Remove duplicates from a list

A

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]

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

Find the idx of the 1st matching element

A

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

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

Remove all elements from a list

A

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

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

Iterate over both the values in a list and their indices

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to concatenate two list

A

the + operator will concatenate 2 lists

one = ['a', 'b', 'c']
two = [1, 2, 3]

one + two # [‘a’, ‘b’, ‘c’, 1, 2, 3]

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

How to manipulate every element in a list with list comprehension

A

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]

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

Count the occurrence of a specific object in a list

A

The count() returne the number of occurrences of a specific object

pets = [‘dog’,’cat’,’fish’,’fish’,’cat’]
pets.count(‘fish’) # 2

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

How to shallow copy a list?

A

.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’]

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

Why create a shallow copy of a list?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to deep copy a list?

A

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’

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

What is the difference bewtween a deep copy and a shallow copy?

A

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.

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

What is the difference between a list and a tuple?

A

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.

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

Return the length of a list

A

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

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

What is the difference between a list and a set?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How to check if an element is not in a list?

A

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

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

Multiply every element in a list by 5 with the map function

A

.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]

26
Q

Combine 2 lists into a list of tuple with the zip function

A

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)]

27
Q

Insert a value at a specific index in an existing list

A

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’]

28
Q

Subtract values in a list from the first element with the reduce function

A

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

29
Q

Remove negative values from a list with the filter function

A

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]

30
Q

Convert a list into a dictionary where list elements are keys

A

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}

31
Q

Modify an existing list with a lambda function

A

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]

32
Q

Remove elements in a list after a specific index

A

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]

33
Q

Remove elements in a list before a specific index

A

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]

34
Q

Remove elements in a list between 2 indices

A

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]

35
Q

Return every 2nd element in a list between 2 indices

A

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]

36
Q

Sort a list of integers in ascending order

A

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]

37
Q

Sort a list of integers in descending order

A

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]

38
Q

Filter even values out of a list with list comprehension

A

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]

39
Q

Count occurrences of each value in a list

A

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})

40
Q

Get the first element from each nested list in a list

A

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]

41
Q

What is the time complexity of insert, find and delete for a list?

A

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.

42
Q

Combine elements in a list into a single string

A

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’

43
Q

What’s the affect of multiplying a list by an integer?

A

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’]

44
Q

Use the “any” function to return True if any value in a list is divisible by 2

A

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

45
Q

Use the “all” function to return True if all values in a list are negative

A

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

46
Q

Can you sort a list with “None” in it?

A

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: ‘

47
Q

What kind of copy would the list constructor create from an existing list?

A

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’]

48
Q

Reverse the order of a list

A

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]

49
Q

What is the difference between reverse and reversed?

A

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]

50
Q

What is the difference between sort and sorted?

A

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]

51
Q

Return the minimum value in a list

A

The min() function returns the minimum value in a list.

li = [10,1,9,2,8,3,7,4,6,5]
min(li) # 1

52
Q

Return the maximum value in a list

A

The max() function returns the maximum value in a list.

li = [10,1,9,2,8,3,7,4,6,5]
max(li) # 10

53
Q

Return the sum of values in a list

A

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

54
Q

Use a list as a stack

A

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’]

55
Q

Find the intersection of 2 lists

A

We can do this by utilizing set() with an ampersand.

li1 = [1,2,3]
li2 = [2,3,4]

set(li1) & set(li2) # {2, 3}

56
Q

Find the difference between a set and another set

A

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}

57
Q

Flatten a list of lists with a list comprehensions

A

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]

58
Q

Generate a list of every integer between 2 values

A

We can create a range between 2 values and then convert that to a list.

list(range(5,10)) # [5, 6, 7, 8, 9]

59
Q

Combine two lists into a dictionary

A

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’}

60
Q

Reverse the order of a list using the slice syntax

A

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’]