Lists Flashcards
Are lists mutable?
yes
copying vs modifying a list
a gotcha in Python lists. What is the result of printing the amazon_cart list after the following code (please explain your reasoning):
amazon_cart = ['book', 'toy', 'pen'] new_cart = amazon_cart
new_cart[0] = ‘microphone’
print(amazon_cart)
amazon_cart would print [‘microphone’, ‘toy’, ‘pen’]
this is because the way we created our variable new_cart. We assigned it to the same memory location as amazon_cart. So, when we change new_cart we are actually changing the data in the memory at the shared memory location.
To avoid this happening, we can create an entirely new list with a separate memory location using list slicing.
new_cart = amazon_cart[:]
What are the List methods? aka built-in actions we can perform on a list in Python
append: changes the list in place. It does not produce a new result
insert: insert an element into a list as a specific index. modifies the list in place and does not create a new copy of the list
extend: extends a list with the iterable argument passed in
pop: removes the last element of a list. If you pass it an index argument it will remove the element at that index. returns the value that was popped
remove: removes the first occurrence of a value passed in as an argument. modifies in place. Does not return anything
clear: removes all elements from the list
index: returns the index location of the value argument passed in. Has optional parameters of start, stop — where stop is exclusive
count: returns the count of how many times an element occurs in the list
sort: modifies the list in place so that the elements are sorted in order
NOTE: Not to be confused with the function SORTED, which takes in an iterable and creates a new sorted copy of the iterable
copy: copies an iterable and returns a new iterable
reverse: reverses the iterable in place.
What does the ‘in’ keyword do?
the keyword ‘in’ checks if a value is in the iterable (string, list, etc)
List slicing
is a way to create a new list
reverse a list using slicing: list_name[::-1]
Common list patterns
- reversing a list using slice.
list_name[::-1] - generate a list quickly
list(range(start, stop)) - create a new string out of a list of items using join method. Join takes an iterable as an argument and joins the elements in the iterable
new_string = ‘ ‘.join([‘my’, ‘focus’, ‘and’, ‘visualization’])
returns ‘my focus and visualization’
list unpacking
a,b,c = [1, 2, 3]
print(a) -> 1
print(b) -> 2
print(c) -> 3
unpack a list but preserve part of the list
a,b,c, *other = [1, 2, 3, 4, 5, 6, 7]
print(a) -> 1
print(other) -> [4, 5, 6, 7]