3-7 Odds and Ends

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:

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:

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:

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:

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.

For lists of numeric values, Python has a built-in function called sum() to calculate their sum:

You can use the + operator to concatenate lists together, just like strings.  For example:

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:

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:

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:

You can also use split() with multi-valued assignment if you don’t want a list:

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 [ ].

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:

However! As with immutable strings, you may not attempt to change an element in a tuple:

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!

    1. 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.
    2. Assume the following statement appears in a program:

      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 (+).
    3. Assume the following statement appears in a program:

      Write a statement that converts this string into the list [‘cookies’, ‘milk’, ‘fudge’, ‘cake’, ‘ice cream’] and displays it.
    4. 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.
    5. 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.