Skip to content

Informatics Practices · Ch 4 — Working with Lists and Dictionaries

Introduction to List

4.1

Introduction to List

A list is Python's way of keeping several values together in a single, ordered container. Formally, the list data type is an ordered sequence which is mutable and is made up of one or more elements. Two words in that definition carry all the weight:

  • Ordered — every element occupies a fixed position in the sequence, so the list remembers the order in which its elements were written. [2, 4, 6] and [6, 4, 2] are different lists.
  • Mutable — the contents of a list can be changed after the list has been created. This sets it apart from types whose values are fixed once made.

How a list differs from a string

A string is also a sequence, but it can consist of characters only. A list has no such restriction: its elements may be of different data types — integers, floats, strings, tuples, or even another list — all sitting side by side in the same list. That freedom is exactly what makes a list so useful for grouping elements of mixed data types: a record like a subject name together with its numeric code, for instance, fits naturally into one list even though its parts are of different types.

Creating a list

The elements of a list are enclosed in square brackets [ ] and are separated by commas. The four lists below show the range of what a list can hold.

A list of values of one type — here, six even numbers:

>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]

A list of strings — the vowels:

>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']

A list mixing data types — an integer, a float and a string together:

>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']

A list of lists, called a nested list — each inner element is itself a complete list. Here every inner list pairs a subject with its code:

>>> list4 = [['Physics',101],['Chemistry',202],['Mathematics',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202], ['Mathematics', 303]]

Notice what nesting buys you: list4 behaves like a small table, where each row (['Physics', 101]) keeps a name and a number bound together, and the outer list keeps the rows in order.

Note

When Python prints a list, it shows it back in square brackets with the elements comma-separated — the same notation used to create it. Strings inside a list are displayed in quotes, which is how you can tell 'Hello' (a string) apart from a name or a number at a glance.

What to remember

  • A list is an ordered, mutable sequence of one or more elements.
  • Unlike a string (characters only), a list may hold integers, floats, strings, tuples, or other lists — in any mix.
  • Lists are written in square brackets with commas between elements.
  • A list whose elements are themselves lists is a nested list — the natural shape for table-like data.