Now that we’ve covered the basics of lists, let’s discuss a few other interesting things you can do with them.
Copying a List
Because lists are mutable, assigning one list variable to another list variable simply makes both variables reference the same list in memory. For example:
1 2 3 |
list1 = [1, 2, 3, 4] list2 = list1 |
After this code, list1 and list2 would both reference the same list object in memory, like so:
This means if you modify list2, then the elements in list1 are also affected, and vice versa.
But suppose you wish to make a copy of the list so that list1 and list2 reference two separate but identical lists. The least efficient way would be to use a loop that copies each element of the list:
1 2 3 4 5 6 7 8 9 10 11 |
list1 = [1, 2, 3, 4] list2 = [ ] print(list1) # displays: [1, 2, 3, 4] print(list2) # displays: [ ] for item in list1: list2.append(item) print(list1) # displays: [1, 2, 3, 4] print(list2) # displays: [1, 2, 3, 4] |
After this code executes, list1 and list2 would reference two different (but identical) lists.
But there’s a better way! A simpler and more elegant approach is to use the concatenation operator or take a slice of the entire list. For example:
1 2 3 4 5 6 7 |
list1 = [1, 2, 3, 4] list2 = [ ] + list1 list3 = list1[:] print(list1) # displays: [1, 2, 3, 4] print(list2) # displays: [1, 2, 3, 4] print(list3) # displays: [1, 2, 3, 4] |
Here list1, list2, and list3 will each refer to their own list object in memory, and all three list-objects will have identical values.
More Fun With Lists
The remove() method allows us to delete a specific item from a list. Sometimes you might need to remove an element at a specific index, regardless of what the item is. This can be accomplished with the pop() method:
1 2 3 4 |
inventory = [ "toothbrush", "suit of armor", "Python book", "light sabre" ] inventory.pop(2) print(inventory) # displays: ['toothbrush', 'suit of armor', 'light sabre'] |
Python also has two built-in functions called min() and max() that work with sequences. They each take a sequence (list or string) as an argument and return the minimum or maximum value in the sequence, respectively.
1 2 3 4 5 6 |
word = "house" print(max(word)) # displays: u my_list = [3.14, 2, 1, 30.5, 20, 10] print(max(my_list)) # displays: 30.5 print(min(my_list)) # displays: 1 |
For lists of numeric values, Python has a built-in function called sum() to calculate their sum:
1 2 3 |
my_list = [3.14, 2, 1, 30.5, 20, 10] print(sum(my_list)) # displays: 66.64 |
You can use the + operator to concatenate lists together, just like strings. For example:
1 2 3 4 5 |
list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 print(list3) # displays: [1, 2, 3, 4, 5, 6, 7, 8] |
Splitting a String
Now that you know all about lists, there is another string method that you will find useful called split(). The split() method returns a list of words in a string. For example:
1 2 3 4 |
my_string = "One Two Three Four" my_list = my_string.split() print(my_list) # displays: [ 'One', 'Two', 'Three', 'Four' ] |
By default, the split() method uses whitespace (space, tab, newline) characters as separators. You can specify a different separator by passing it as an argument. For example, suppose you have a string containing a date, and you’d like to break out the month, day, and year as items in a list:
1 2 3 4 |
date_string = '09/01/2018' date_list = date_string.split('/') print(date_list) # displays: ['09', '01', '2018'] |
Note that each list element is still a string, so you would need to then covert each to an integer if you wanted to use it in a calculation, like this:
1 2 3 4 5 |
# Converting List of Strings Into List of Integers for index in range(len(date_list)): date_list[index] = int(date_list[index]) print(date_list) # displays: [9, 1, 2018] |
You can also use split() with multi-valued assignment if you don’t want a list:
1 2 3 4 5 6 7 |
date_string = '09/01/2018' day, month, year = date_string.split('/') print(int(day)) # displays: 9 print(int(month)) # displays: 1 print(int(year)) # displays: 2018 |
Tuples
Before we finish off, I want to mention another sequence data type in Python called the tuple. The best way to think of a tuple is as an immutable list. A tuple is created in the same way as a list, except we use parentheses ( ) instead of square brackets [ ].
1 2 3 4 |
inventory = ( "toothbrush", "suit of armor", "Python book", "light sabre" ) # displays: ('toothbrush', 'suit of armor', 'Python book', 'light sabre') print(inventory) |
With a tuple you can use the built-in len() function, the in operator, slice it, and concatenate (+) it with another tuple — much the same way strings work. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
inventory = ( "toothbrush", "suit of armor", "Python book", "light sabre" ) print("Your inventory is now:", inventory) # get the length of a tuple print("You have", len(inventory), "items in your possession.") # test for membership with in if "healing potion" in inventory: print("You will live to fight another day.") # display one item through an index index = int(input("\nEnter the index number for an item in inventory: ")) print("At index", index, "is", inventory[index]) # display a slice begin = int(input("\nEnter the index number to begin a slice: ")) end = int(input("Enter the index number to end the slice: ")) print("inventory[", begin, ":", end, "]\t\t", end="") print(inventory[begin:end]) # concatenate two tuples chest = ("gold", "gems") print("You find a chest. It contains:", chest) print("You add the contents of the chest to your inventory.") inventory += chest print("Your inventory is now:", inventory) |
However! As with immutable strings, you may not attempt to change an element in a tuple:
1 |
inventory[1] = "robotic exoskeleton" # Exception: TypeError! |
Because tuples are immutable, all of the list methods [append(), insert(), remove(), and reverse()] are not available for tuple objects.
Now you might be wondering if lists can do everything tuples can do and more, why bother with tuples at all? I’m glad you asked!
The Python interpreter deals with tuples faster than lists because it never has to worry that the data within a tuple object will change. For this reason, you will often see a tuple used when it defines a constant set of values in a program. If you think about it, this can make your code safer because you can protect data that you don’t want to be changed by putting it into a tuple instead of a list.
Data Type Round-Up!
We’ve discussed integers, floats, strings, Booleans, lists, and tuples.. whew! Let’s recap what we know about these types so that we can see how they fit together. There are three ways that one can look at a data type in Python:
-
- What They Store: A data type can either store a single value (int, float, bool) or hold multiple values (strings, lists, tuples).
- How They Are Updated: A data type can either be immutable (int, float, bool, string, tuple) or mutable (lists). We have learned that if you pass an immutable type into a function, and the function attempts to change the parameter variable, then the original value passed into the function is not changed. We called this pass-by-value. We also learned that if you pass a mutable type into a function, and the function attempts to change the parameter variable, then the original value passed into the function is changed. We called this pass-by-reference.
- How Data Is Accessed: A data type can either be accessed directly using the variable name (int, float, bool) or using an index (strings, lists, tuples).
This table summarizes all that we have learned about Python data types:
You Try!
-
- Start a new page in your Learning Journal titled “3-7 Odds and Ends“. Carefully read the notes above and in your own words summarize the key ideas from each section.
- Assume the following statement appears in a program:
1names = [ "Vik-20" ]
Write 3 statements to demonstrate how to add your name to the end of the list in 3 different ways: using the insert() method, using the append() method, and using list concatenation (+). - Assume the following statement appears in a program:
1my_string = "cookies>milk>fudge>cake>ice cream"
Write a statement that converts this string into the list [‘cookies’, ‘milk’, ‘fudge’, ‘cake’, ‘ice cream’] and displays it. - Write a program that asks the user to enter 5 unique numbers. Use a list to keep track of numbers already seen. If a number has already been seen ask for a new number. After 5 unique numbers have been entered display the list.
- Extra Challenge: Write a Word Jumble Game that chooses a random word from a list of words you have defined, and then remove the word from the list. The computer should display a jumble of the word (reuse your work from U3-5 Q4), and ask the user to guess what the word is. Once the player has guessed the word, another random word should be selected from the list and the game continues until the list of words is empty.