Lists Flashcards
What is the format for defining lists?
Lists are defined using the squared brackets [ ]
How do you add an element to the end of a list?
You add an element to the end of a list by using the append method or using concatenation
my_list = [1, 2, 3]
my_list.append(4) OR my_list + [4] OR my_list += [4]
# my_list is now [1, 2, 3, 4]
How can you extend a list with elements of another list?
You can extend a list with the elements of another iterable using the extend()
method or the +=
operator.
my_list = [1, 2, 3], my_other_list = [4, 5]
my_list.extend([4, 5]) OR my_list += my_other_list
my_list is now [1, 2, 3, 4, 5]
How do you add an element at a specific index?
You can insert an element at a specific index using the insert()
method.
my_list = [1, 2, 3]
my_list.insert(1, 4)
# my_list is now [1, 4, 2, 3]
How can you change an element at a specific index in a list?
You can update the value of an element at a specific index by assigning a new value directly to that index.
my_list = [1, 2, 3]
my_list[1] = 4
# my_list is now [1, 4, 3]
What are the methods for removing elements from a list?
The methods for removing elements from a list are remove() pop() and del()
How can you remove an element from a list at a specific point?
The remove() method removes the first occurrence of a specific value.
my_list = [1, 2, 3, 2]
my_list.remove(2)
# my_list is now [1, 3, 2]
How do you return and remove an element from a list?
The pop() method removes and returns an element at a specific index.
my_list = [1, 2, 3]
popped_element = my_list.pop(1)
# my_list is now [1, 3] and popped_element is 2
What method can be used to remove elements either by index or to clear an entire list?
The del() method can be used to remove elements by index or to clear the entire list.
my_list = [1, 2, 3]
del my_list[1]
# my_list is now [1, 3]
del my_list[:]
# my_list is now []
What can be used to update multiple elements at once or to replace a portion of a list with another list?
You can use slicing to update multiple elements at once or to replace a portion of the list with another iterable.
my_list = [1, 2, 3, 4, 5]
my_list[1:4] = [10, 20, 30]
# my_list is now [1, 10, 20, 30, 5]
How can List Comprehensions be used to update all elements in a list?
my_list = [1, 2, 3]
updated_list = [x * 2 for x in my_list]
# updated_list is [2, 4, 6]
Lists are mutable. What does mutable mean?
Mutable means it can be updated.