Python Basics #8 — Lists

7 min read

In this lesson we’ll cover one of Python’s most important data structures: the list.

A list is a collection of Python objects. Put differently, it’s a data structure that lets you store and reference many different kinds of data in one place.

What is a list? #

  • A list is one of the most important data structures.
  • A list is a collection of objects.
  • A list is a sequence type.
  • A list is an iterator object.

Now let’s see how to define a list. A list uses square brackets with comma-separated items. Let’s start with an empty list. There are two ways to create one: with empty brackets, or with the list() constructor.

First, with empty brackets:

>>> []
[]

Now with the list constructor:

>>> list()
[]

In real programs you’ll often need to define an empty list, so remember both patterns. Either works, but many Python programmers prefer empty brackets because they’re faster.

Let’s compare performance:

# Run the code below in IPython or Notebook.
In [1]: %timeit []
21.2 ns ± 0.419 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit list()
52.9 ns ± 0.601 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Empty brackets are clearly faster, but we’re talking nanoseconds — not seconds, not even milliseconds. Either approach is fine.

Now let’s define a simple list with the numbers 1 to 5 and print it:

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

The variable now holds the integers 1 through 5. Use the type function to check:

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

Confirmed — it’s a list.

Now let’s look at basic list features and the methods provided by the list class.

The Python built-in len function returns the number of items in the list — its length. Let’s check the length of the list we just defined:

>>> len(numbers)
5

The list has 5 items.

Python provides the built-in sorted function for sorting list items in order:

>>> # Define five numbers in arbitrary order.
>>> numbers = [3, 2, 1, 5, 4]
>>> # Sort the list using sorted.
>>> sorted(numbers)
[1, 2, 3, 4, 5]

Important: sorted returns a new sorted list — the original list is NOT modified.

Let’s verify the original list is unchanged:

>>> numbers
[3, 2, 1, 5, 4]

As you can see, the original is intact. If you want to sort the original list in place (rather than receive a new sorted list), use the sort class method instead. But note that sort modifies the original and returns nothing.

Sort the original list in place:

>>> numbers.sort()
>>> numbers
[1, 2, 3, 4, 5]

The original list is now sorted.

Built-in max and min return the maximum and minimum items in the list.

Print the max:

>>> max(numbers)
5

Print the min:

>>> min(numbers)
1

Built-in sum returns the sum of all items:

>>> sum(numbers)
15

Now let’s look at basic list features. A list is one of Python’s six sequence types. Another sequence type we covered earlier is string. The dictionary defines “sequence” as an arrangement, ordering, succession, or series of related events. So a sequence type is one that manages data in an ordered arrangement. Because items are ordered, you can access internal items with numeric indexes.

Just as with strings, you can access list items by index — and you can also slice them. Python uses zero-based indexing, so the leftmost item has index 0 and the index increases by 1 to the right (covered in the previous lesson). Reverse indexing lets you access items starting from the last.

Python sequence types #

  • str
  • unicode
  • list
  • tuple
  • buffer
  • range

Define numbers 1 to 5 again:

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

Print the first item, 1:

>>> numbers[0]
1

Print the last item, 5:

>>> numbers[4]
5

Use a reverse index to print the last item:

>>> numbers[-1]
5

Slice the first 3 items:

>>> numbers[0:3]
[1, 2, 3]

When start is 0, you can omit it:

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

Print the last 3 items:

>>> numbers[-3:]
[3, 4, 5]

Now let’s look at the most important list feature: iteration.

Some Python objects can be used in a for loop — these are called iterator objects. A list is an iterator object, so you can use a for loop to access each item. Use iter to confirm whether something is an iterator object:

>>> iter(numbers)
<list_iterator object at 0x7fee58134a30>

Confirmed — the list is iterable.

Now let’s check whether a string is also iterable:

>>> iter('string')
<str_iterator object at 0x7fee58134790>

Now use a for loop to print each item in the list:

>>> for i in numbers:
...     print(i)
...
1
2
3
4
5

Strings are iterable too, so you can use a for loop on them:

>>> for i in 'string':
...     print(i)
...
s
t
r
i
n
g

Next is concatenation. Use the + operator to combine two lists into one:

>>> list_1 = [1, 2, 3]
>>> list_2 = [4, 5]
>>> new_list = list_1 + list_2
>>> new_list
[1, 2, 3, 4, 5]

You can also use the * (asterisk) operator to repeat list items:

>>> new_list * 3
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

The entire list is repeated 3 times.

Basic list features #

  • Indexing
  • Slicing
  • Iterating
  • Concatenating
  • Multiplying

Built-in functions usable with lists #

  • len
  • sorted
  • max
  • min
  • sum

Now let’s use the class methods.

First, use help to check what methods the list class provides:

>>> help(list)
Help on class list in module builtins:

class list(object)
|  list(iterable=(), /)
|
|  Built-in mutable sequence.
|
|  If no argument is given, the constructor creates a new empty list.
|  The argument must be an iterable if specified.
|
|  Methods defined here:
|
|  __add__(self, value, /)
|      Return self+value.
|
|  __contains__(self, key, /)
|      Return key in self.
|
|  __delitem__(self, key, /)
|      Delete self[key].
|
|  __eq__(self, value, /)
|      Return self==value.
|
:

First, append adds a new item to a list:

>>> numbers = [1, 2, 3, 4, 5]
>>> numbers.append(6)
>>> numbers
[1, 2, 3, 4, 5, 6]

The new item 6 was added at the end.

Now use extend to concatenate a list with another list:

>>> numbers.extend([7, 8])
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8]

The two lists were combined into one.

You can also concatenate two lists using the + operator.

💡 Today’s tip

To combine two lists, use extend or the + operator. Do not use append for this!

A common beginner mistake: using append to combine two lists. Let’s see what actually happens when you do that:

>>> numbers.append([9, 10])
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, [9, 10]]

As you can see, append doesn’t combine the two lists — it adds the second list as a single element at the end of the first list. Be careful.

To insert a new item at a specific position, use insert. The first argument is the index where the new item will go; the second is the value.

>>> numbers = [1, 2, 4, 5]
>>> numbers.insert(2, 3)
>>> numbers
[1, 2, 3, 4, 5]

Now remove to delete an item. remove takes the value of the item to delete — not its index.

X