Python Programming/Lists

A list in Python is an ordered group of items (or elements). It is a very general structure, and list elements don't have to be of the same type: you can put numbers, letters, strings and nested lists all on the same list.

Overview
Lists in Python at a glance:

List creation
There are two different ways to make a list in Python. The first is through assignment ("statically"), the second is using list comprehensions ("actively").

Plain creation
To make a static list of items, write them between square brackets. For example:

Observations:


 * 1) The list contains items of different data types: integer, string, and Donkey class.
 * 2) Objects can be created 'on the fly' and added to lists. The last item is a new instance of Donkey class.

Creation of a new list whose members are constructed from non-literal expressions:

List comprehensions
Using list comprehension, you describe the process using which the list should be created. To do that, the list is broken into two pieces. The first is a picture of what each element will look like, and the second is what you do to get it.

For instance, let's say we have a list of words:

To take the first letter of each word and make a list out of it using list comprehension, we can do this:

List comprehension supports more than one for statement. It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest.

List comprehension supports an if statement, to only include members into the list that fulfill a certain condition:

In version 2.x, Python's list comprehension does not define a scope. Any variables that are bound in an evaluation remain bound to whatever they were last bound to when the evaluation was completed. In version 3.x Python's list comprehension uses local variables:

This is exactly the same as if the comprehension had been expanded into an explicitly-nested group of one or more 'for' statements and 0 or more 'if' statements.

List creation shortcuts
You can initialize a list to a size, with an initial value for each element:

This works for any data type:

But there is a caveat. When building a new list by multiplying, Python copies each item by reference. This poses a problem for mutable items, for instance in a multidimensional array where each element is itself a list. You'd guess that the easy way to generate a two dimensional array would be:

and this works, but probably doesn't do what you expect:

What's happening here is that Python is using the same reference to the inner list as the elements of the outer list. Another way of looking at this issue is to examine how Python sees the above definition:

Assuming the above effect is not what you intend, one way around this issue is to use list comprehensions:

List size
To find the length of a list use the built in len method.

Combining lists
Lists can be combined in several ways. The easiest is just to 'add' them. For instance:

Another way to combine lists is with extend. If you need to combine lists inside of a lambda, extend is the way to go.

The other way to append a value to a list is to use append. For example:

However, [3,4] is an element of the list, and not part of the list. append always adds one element only to the end of a list. So if the intention was to concatenate two lists, always use extend.

Continuous slices
Like strings, lists can be indexed and sliced:

Much like the slice of a string is a substring, the slice of a list is a list. However, lists differ from strings in that we can assign new values to the items in a list:

We can assign new values to slices of the lists, which don't even have to be the same length:

It's even possible to append items onto the start of lists by assigning to an empty slice:

Similarly, you can append to the end of the list by specifying an empty slice after the end:

You can also completely change the contents of a list:

The right-hand side of a list assignment statement can be any iterable type:

With slicing you can create copy of list since slice returns a new list:

Note, however, that this is a shallow copy and contains references to elements from the original list, so be careful with mutable types:

Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence of a list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the slice to be operated upon.

Comparing lists
Lists can be compared for equality.

Lists can be compared using a less-than operator, which uses lexicographical order:

Sorting lists
Sorting at a glance:

Sorting lists is easy with a sort method.

Note that the list is sorted in place, and the sort method returns None to emphasize this side effect.

If you use Python 2.4 or higher there are some more sort parameters:
 * sort(cmp,key,reverse)
 * cmp : function to determine the relative order between any two elements
 * key : function to obtain the value against which to sort for any element.
 * reverse : sort(reverse=True) or sort(reverse=False)

Python also includes a sorted function.

Note that unlike the sort method, sorted(list) does not sort the list in place, but instead returns the sorted list. The sorted function, like the sort method also accepts the reverse parameter.

Links:
 * 2. Built-in Functions # sorted, docs.python.org
 * Sorting HOW TO, docs.python.org

Iteration
Iteration over lists:

Read-only iteration over a list, AKA for each element of the list:

Writable iteration over a list:

From a number to a number with a step:

For each element of a list satisfying a condition (filtering):

See also ../Loops.

Removing
Removing aka deleting an item at an index (see also ):

Removing an element by value:

Creating a new list by copying a filtered selection of items from the old list: This uses a list comprehension.

Update a list by retaining a filtered selection of items in it by using "[:]":

For more complex condition a separate function can be used to define the criteria:

Removing items while iterating a list usually leads to unintended outcomes unless you do it carefully by using an index:

Links:
 * Remove items from a list while iterating, stackoverflow.com

Aggregates
There are some built-in functions for arithmetic aggregates over lists. These include minimum, maximum, and sum: The max and min functions also apply to lists of strings, returning maximum and minimum with respect to alphabetical order:

Copying
Copying AKA cloning of lists:

Making a shallow copy:

The above does not make a deep copy, which has the following consequence:

Making a deep copy:

See also.

Links:
 * 8.17. copy — Shallow and deep copy operations at docs.python.org

Clearing
Clearing a list:

Clearing using a proper approach makes a difference when the list is passed as an argument:

Keywords: emptying a list, erasing a list, clear a list, empty a list, erase a list.

Removing duplicate items
Removing duplicate items from a list (keeping only unique items) can be achieved as follows.

If each item in the list is hashable, using list comprehension, which is fast:

If each item in the list is hashable, using index iteration, much slower:

If some items are not hashable, the set of visited items can be kept in a list:

If each item in the list is hashable and preserving element order does not matter:

In the above examples where index iteration is used, scanning happens from the end to the beginning. When these are rewritten to scan from the beginning to the end, the result seems hugely slower.

Links:
 * How do you remove duplicates from a list? at python.org Programming FAQ
 * Remove duplicates from a sequence (Python recipe) at activestate.com
 * Removing duplicates in lists at stackoverflow.com

append(x)
Add item x onto the end of the list.

See pop(i)

pop(i)
Remove the item in the list at the index i and return it. If i is not given, remove the last item in the list and return it.

+
To concatenate two lists.

*
To create a new list by concatenating the given list the given number of times. i.e. list1 * 0 == []; list1 * 3 == list1 + list1 + list1;

in
The operator 'in' is used for two purposes; either to iterate over every item in a list in a for loop, or to check if a value is in a list returning true or false.

Difference
To get the difference between two lists, just iterate:

Intersection
To get the intersection between two lists (by preserving its elements order, and their doubles), apply the difference with the difference:

Exercises

 * 1) Use a list comprehension to construct the list ['ab', 'ac', 'ad', 'bb', 'bc', 'bd'].
 * 2) Use a slice on the above list to construct the list ['ab', 'ad', 'bc'].
 * 3) Use a list comprehension to construct the list ['1a', '2a', '3a', '4a'].
 * 4) Simultaneously remove the element '2a' from the above list and print it.
 * 5) Copy the above list and add '2a' back into the list such that the original is still missing it.
 * 6) Use a list comprehension to construct the list ['abe', 'abf', 'ace', 'acf', 'ade', 'adf', 'bbe', 'bbf', 'bce', 'bcf', 'bde', 'bdf']

Solutions
Question 1 : List1 = [a + b for a in 'ab' for b in 'bcd'] print(List1) >>> ['ab', 'ac', 'ad', 'bb', 'bc', 'bd'] Question 2 : List2 = List1[::2] print(List2) >>> ['ab', 'ad', 'bc'] Question 3 : List3 = [a + b for a in '1234' for b in 'a'] print(List3) >>> ['1a', '2a', '3a', '4a'] Question 4 : print(List3.pop(List3.index('3a'))) print(List3) >>> 3a >>> ['1a', '2a', '4a'] Question 5 : List4 = List3[:] List4.insert(2, '3a') print(List4) >>> ['1a', '2a', '3a', '4a'] Question 6 : List5 = [a + b + c for a in 'ab' for b in 'bcd' for c in 'ef'] print(List5) >>> ['abe', 'abf', 'ace', 'acf', 'ade', 'adf', 'bbe', 'bbf', 'bce', 'bcf', 'bde', 'bdf']