Lists

Combine a list of lists

A list of lists can be combined using sum() and an empty list. This works on a dict values list of lists also.

Example

cars = {
    'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
    'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
    'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
    'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
    'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']
}

>>> cars.values()
dict_values([['Falcon', 'Focus', 'Festiva', 'Fairlane'],
             ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
             ['Maxima', 'Pulsar', '350Z', 'Navara'],
             ['Civic', 'Accord', 'Odyssey', 'Jazz'],
             ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']])

>>> sum(cars.values(),[])
['Falcon', 'Focus', 'Festiva', 'Fairlane',
 'Commodore', 'Captiva', 'Barina', 'Trailblazer',
 'Maxima', 'Pulsar', '350Z', 'Navara',
 'Civic', 'Accord', 'Odyssey', 'Jazz',
 'Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']

Use the plus sign to join lists into one list.

>>> [1,2] + [3,4]
[1, 2, 3, 4]

Sorting Lists

Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.

sorted() returns a new list:

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

sort() modifies the list:

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

The list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.

Sorting examples

>>> games_won = [('julian', 3), ('bob', 1), ('jim', 1), ('sara', 0), ('tim', 5)]
>>> sorted(games_won)
[('bob', 1), ('jim', 1), ('julian', 3), ('sara', 0), ('tim', 5)]

Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.

For example, here’s a case-insensitive string comparison:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']