Working with Lists
Unlike strings, lists are mutable. This means we can change the values of the elements inside the list, add new elements to the list, remove items from the list, or change the order of the elements.
Changing One Element
To update a single item in a list, use the syntax:
list_name[index] = new_value
list_name[index]
identifies the element in the list that we want to change.
The =
operator assigns new_value
to that index location.
|
|
Console Output
['granola bars', 'veggies', 'TP', 'other healthy stuff']
['pears', 'veggies', 'TP', 'chocolate']
Removing Elements
To remove one or more elements from a list, we can use the del
function.
Here, del
stands for delete.
The general syntax is:
del list_name[index] # Removes the element at index.
del list_name[start:end] # Removes the elements from the 'start' index up to but
# NOT including the 'end' index.
Note that del
does NOT use parentheses ()
.
|
|
Console Output
['one', 'three']
['a', 'z']
The Slice Operator
Used on the right hand side of the =
operator, a slice returns a smaller
portion of a list.
new_list = old_list[start : end]
Used on the left hand side of the =
operator, a slice will either
insert, replace, or remove elements.
The general syntax is:
list_name[start : end] = [new values...]
Note that the new values must be inside brackets []
and separated from each
other by commas.
Inserting New Elements
Make the start
and end
values the same. This inserts all of the new
values into the list, starting at the chosen index. Existing elements get
pushed to later positions in the list.
|
|
Console Output
[3, 6, 9, 12]
[3, 6, 'a', 'b', 'cde', 9, 12]
Replacing Elements
Make the start
and end
values different. The elements from index
start
to end
(NOT including end
) get replaced with the new values.
Note that the number of old and new values can be different.
|
|
Console Output
[10, 20, 30, 40, 50, 60, 70, 80]
[10, -1, -3, 70, 80]
Check Your Understanding
What is printed by the following code?
|
|
- [4, 2, True, 8, 6, 5, 4]
- [4, True, 2, 8, 6, 5, 4]
- [4, 2, True, 6, 5, 4]
- [4, True, 8, 6, 5, 4]
In the following code, we want to add 'B'
and 'b'
to the beginning
of b_list
without losing any of the other items.
b_list = ['barber', 'baby', 'bubbles', 'bumblebee']
b_list[start_index : end_index] = ['B', 'b']
What values should we use for start_index
and end_index
?
- [0 : 0]
- [0 : 1]
- [1 : 1]
- [0 : ]
- [ : 1]