Lists

What is a list?

A list is a data structure that stores a number of items in a sequential form. Lists are useful for collecting variables together for processing as a whole.

When should I use a list?

Lists should be used when you need to collect variable values together in one place. Some examples:

  • For storing a number of values entered by the user
  • To store a set of co-ordinates that make up a shape
  • To collect items of interest from a dataset (parse through some text, store long words in a list)

What can lists do?

Quite a few things.

List construction:

Interactive session:

>>> mylist = ["a", "b", "c", "d"]
>>> print mylist
['a', 'b', 'c', 'd']
>>> mylist = ["a"] * 4
>>> print mylist
['a', 'a', 'a', 'a']
>>>
>>> mylist = ["a"] * 3 + ["b"]
>>> print mylist
['a', 'a', 'a', 'b']

List access

Interactive session:

>>> mylist = ["a", "b", "c", "d"]
>>> mylist[0]
'a'
>>> mylist[3]
'd'
>>> mylist[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range
>>> mylist[-1]
'd'

Other list operations

List length:

>>> mylist = ["a", "b", "c", "d"]
>>> print len(mylist)
4

Sorting:

>>> mylist = ["d", "b", "c", "a"]
>>> mylist.sort()
>>> print mylist
['a', 'b', 'c', 'd']

List slicing

List slicing is a way to get access to a few items of a list at once:

>>> mylist = ["a", "b", "c", "d"]
>>> mylist[0:2]
['a', 'b']
>>> mylist[1:2]
['b']
>>> mylist[:-1]
['a', 'b', 'c']
>>> mylist[::-1]
['d', 'c', 'b', 'a']
>>> mylist[2:]
['c', 'd']
>>>

Lists in other languages

Not all languages have lists as a data type like Python does. Other languages use a thing called an "array" which is like a list but much less flexible and (as a result) much more efficient for the machine to process. These languages often implement lists separately, so you have the choice of a flexible slow data structure (list) or an awkward fast one (array).

More help

The web is your friend.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License