Continuing from the previous post Python Lists, we will look at some more things you can do with them.
Lists, unlike strings, are mutable. This means that you can change a list in place without reassigning the list to a new variable. To change a list in place you need to know the index you want to change. Take this list:
shopping_list = ['Milk', 'Cookies', 'Bread', 'Steak', 'Chicken', 'Shrimp', 'Cheese']
After creating this list, we realize that someone has a shellfish allergy. So we need to remove Shrimp. We could reassign the variable shopping_list
and change Shrimp to something else. While that works, think about this running in a script. This is inefficient, and it could have a cost depending on how large the list is. We can use slicing to find the element we want to replace and replace it. To replace shrimp, we will call the variable name and, in brackets, put the index we want to replace. Then put a single equals sign and then the new element you want in the list.
Let us replace Shrimp with Soda:
shopping_list[5] = 'Soda'
When we look at the shopping list now:
shopping_list
['Milk', 'Cookies', 'Bread', 'Steak', 'Chicken', 'Soda', 'Cheese']
As with strings, you can also concatenate lists to create new lists. If we have the following two lists and want to concatenate them:
lst_10 = [1,2,3]
lst_11 = [4,5,6]
lst_10+lst_11
[1, 2, 3, 4, 5, 6]
Now, what if a list has different data types in it, like strings and integers:
lst_str = ['Cat', 'Dog', 'Bird']
lst_int = [1,2,3]
lst_str+lst_int
['Cat', 'Dog', 'Bird', 1, 2, 3]
Why? In Strings, Strings, and More Strings Part Deux, didn’t you say that the data types had to be the same? They do; the data type we are concatenating here is of type list.
type(lst_str)
<class 'list'>
type(lst_int)
<class 'list'>
It doesn’t matter what the elements are inside the list; as long as the data type is the same, you can concatenate it. This concept is important. You can concatenate these two objects because they are of the type list.
If the need so fills your soul, you can also repeat the list with the *
operator
lst_str * 3
['Cat', 'Dog', 'Bird', 'Cat', 'Dog', 'Bird', 'Cat', 'Dog', 'Bird']
More about Python lists can be found on Python’s documentation site: https://www.python.org.