Lists

Building Up A List

Lists in Python are ordered collections of things. We can create lists using square brackets ([]).

>>> numbers = [1, 2, 3]

Just like every other object, we can use type to confirm that we’re working with a list:

>>> type(numbers)
<class 'list'>

This is an empty list object:

>>> numbers = []

We can add a new item to the end of a list using the append method:

>>> numbers.append(3)
>>> numbers
[3]
>>> numbers.append(7)
>>> numbers
[3, 7]
>>> numbers.append(2)
>>> numbers
[3, 7, 2]

List Basics

It’s possible (though unusual) to store objects of different types in a list:

>>> things = [5, True, "hello"]
>>> things
[5, True, 'hello']

The above list contains references to three elements: the integer 5, the boolean value True, and the string "hello".

Like strings, lists have a length.

>>> len(things)
3

Also like strings, lists can be checked for containment.

>>> 5 in things
True
>>> False in things
False
>>> "hello" in things
True

Lists are ordered. We can access individual items in lists based on their position.

Lists are zero-indexed so the first item has an index of zero.

>>> things[0]
5
>>> things[2]
'hello'

If we try to access an element outside of our list, we’ll get an exception.

>>> things[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Elements of the list can be of different types:

>>> type(things[0])
<class 'int'>
>>> type(things[1])
<class 'bool'>

We can change items in our lists using a syntax similar to setting variables:

>>> things[1] = False
>>> things
[5, False, 'hello']

Last List Element

Let’s say we have access to a list and we don’t know much about it.

How can we get the last element from our list?

One way:

>>> things[len(things) - 1]
'hello'

Python gives us a shortcut though. We can use negative indexes to start counting from the end of our list.

To get the last element we can use index -1:

>>> things[-1]
'hello'

Negative indexing starts from the end of the string and counts in backwards:

>>> things[-2]
False

List Methods

As we saw previously, we can add things to the end of our list using the append method.

>>> things.append("something else")

In terms of efficiency for adding and removing items, lists are essentially stacks. Adding an item to the end and removing an item from the end are inexpensive operations. To remove the end of the list, we use pop.

>>> things.pop()
'something else'
>>> things
[5, False, 'hello']
>>> things.pop(1)
False
>>> things
[5, 'hello']

When we use the pop method, Python returns the item that was “popped”. If we want to remove a different item, we can give pop an index to use.

Many programming languages have push and pop, but Python (somewhat strangely) uses append, instead of push.

Strings have a method called join which allows us to join a collection of string items together, delimiting them with the initial string characters. Let’s use it with a list:

>>> words = ["these", "are", "some", "words"]
>>> " ".join(words)
'these are some words'
>>> "#".join(words)
'these#are#some#words'
>>> "...".join(words)
'these...are...some...words'

Since strings are themselves a collection of characters, we can also use the join method on a string:

>>> the_word = "bird"
>>> " ".join(the_word)
'b i r d'

Lists have other methods too. If we want to see other methods that lists have we can use the help function.

Remember that we can use arrows to move up and down in help and q to quit help. Vim keyboard shortcuts also work.

We can use help on the list function:

>>> help(list)

Or we can use help directly on our list instance variable. We’ll get the same thing both ways.

>>> help(things)

We could also find out more about lists by searching the Python documentation.

When searching for Python documentation, use a search engine like Google or DuckDuckGo. Python’s documentation search is not very good.

List Exercises

Combined Lists

File: Edit the combine_lists function in the lists.py file that is in the exercises directory.

Test: Run python test.py combine_lists in your exercises directory.

Exercise: The function combine_lists should take two lists and return a new list containing all elements from both lists. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:

>>> from lists import combine_lists
>>> first = [1, 2, 3]
>>> second = [4, 5, 6]
>>> combine_lists(first, second)
[1, 2, 3, 4, 5, 6]

Note

Want to test this out manually (instead of using python test.py)?

You could could create a file called combine_lists_test.py with your own test code:

from lists import combine_lists

print("Calling combine_lists([1, 2, 3], [4, 5, 6])")
print("Expected: [1, 2, 3, 4, 5, 6]")
print("  Actual:", repr(combine_lists([1, 2, 3], [4, 5, 6])))

Then you can run that file to test your code:

$ python combine_lists_test.py

Rotate

File: Edit the rotate_list function in the lists.py file that is in the exercises directory.

Test: Run python test.py rotate_list in your exercises directory.

Exercise: The function rotate_list should remove the first item from a given list, add it to the end of the list, and return the item. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:

>>> from lists import rotate_list
>>> numbers = [1, 2, 3, 4]
>>> rotate_list(numbers)
1
>>> numbers
[2, 3, 4, 1]
>>> rotate_list(numbers)
2
>>> numbers
[3, 4, 1, 2]

Reverse rotate

File: Edit the rotate_list function you just changed in the lists.py file that is in the exercises directory.

Test: Run python test.py rotate_list in your exercises directory.

Note

To run tests for this updated program, open lists_test.py, find the line that starts with class RotateListTests. Comment out the 2 lines with @unittest.skip to enable the tests for Reverse Rotate. These lines told the Test Framework to skip the tests because we didn’t expect the test to pass, but now we are changing the program so the test should pass, therefore we comment the line out.

Exercise: Modify rotate_list to accept a reverse argument which, if True, removes the last item (instead of the first) and adds the item to the beginning of the list (instead of the end). To test the function in the REPL, you can paste the function in from your text editor or import it as shown below.

>>> from lists import rotate_list
>>> numbers = [1, 2, 3, 4]
>>> rotate_list(numbers, reverse=True)
4
>>> numbers
[4, 1, 2, 3]
>>> rotate_list(numbers, reverse=False)
4
>>> numbers
[1, 2, 3, 4]

Characters

File: Edit the characters function in the lists.py file that is in the exercises directory.

Test: Run python test.py characters in your exercises directory.

Exercise: The function characters takes a string and returns a list where each item is a single character from the string. All characters should be lowercased. Your function should accept an optional sort argument that, when True, will return the characters in ASCII-betical sorted order.

>>> from lists import characters
>>> characters("Trey Hunner")
['t', 'r', 'e', 'y', ' ', 'h', 'u', 'n', 'n', 'e', 'r']
>>> characters("Trey Hunner", sort=True)
[' ', 'e', 'e', 'h', 'n', 'n', 'r', 'r', 't', 'u', 'y']
>>> characters("hello", sort=False)
['h', 'e', 'l', 'l', 'o']
>>> characters("hello", sort=True)
['e', 'h', 'l', 'l', 'o']

Reverse word order

File: Edit the reverse_words function in the lists.py file that is in the exercises directory.

Test: Run python test.py reverse_words in your exercises directory.

Exercise: The function reverse_words takes a string of words and returns a new sentence with the order of the words reversed. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:

>>> from lists import reverse_words
>>> reverse_words("words some are these")
'these are some words'
>>> reverse_words("who is this")
'this is who'

Power By Index

File: Edit the ith_item_power function in the lists.py file that is in the exercises directory.

Test: Run python test.py ith_item_power in your exercises directory.

Exercise: The function ith_item_power accepts a list of numbers and an index number and returns the i-th element raised to the i-th power where i is the given index number. To test the function in the REPL, you can paste the function in from your text editor or import it as shown:

>>> from lists import ith_item_power
>>> ith_item_power([3, 2, 5], 2)
25
>>> ith_item_power([5, 6, 2, 7, 3], 4)
81

Natural Sort

Edit the natural_sort function in lists.py so that when given a list of words, it returns a new list with the words in “natural” sorted order. In other words, the new list will have the words sorted with the case of the words ignored.

Hint: Python has a built-in function sorted. However, when strings are sorted directly, all upper case letters come before lower case letters. You will need to create a key function to give to the sorted function as an argument. The key function for sorted accepts one item from the list, and returns the value that should be used for the sort.

To test with the automated tests, run python test.py natural_sort from the command line.

To test the function in the REPL, you can paste the function in from your text editor or import it as shown:

>>> from lists import natural_sort
>>> fruits = ['Kiwi', 'orange', 'apple', 'Apricot', 'Grape', 'guava']
>>> sorted(fruits)
['Apricot', 'Grape', 'Kiwi', 'apple', 'guava', 'orange']
>>> natural_sort(fruits)
['apple', 'Apricot', 'Grape', 'guava', 'Kiwi', 'orange']