Home > Articles > Open Source > Python

  • Print
  • + Share This
Like this article? We recommend

Lists and Tuples

Just as strings are sequences of characters, lists and tuples are sequences of arbitrary objects. You create a list as follows:

names = [ "Dave", "Mark", "Ann", "Phil" ]

Lists are indexed by integers starting with zero. Use the indexing operator to access and modify individual items of the list:

a = names[2]       # Returns the third item of the list, "Ann"
names[0] = "Jeff"    # Changes the first item to "Jeff"

The length of a list can be obtained using the len() function:

print len(names)    # prints 4

To append new items to a list, use the append() method:


To insert an item into the list, use the insert() method:

names.insert(2, "Sydney")

You can extract or reassign a portion of a list by using the slicing operator:

# Returns [ "Jeff", "Mark" ]
b = names[0:2]

# Returns [ "Sydney", "Ann", "Phil", "Kate" ]
c = names[2:]

# Replace the 2nd item in names with 'Jeff'
names[1] = 'Jeff'

# Replace the first two items of the list with
# the list on the right
names[0:2] = ['Dave','Mark','Jeff']

Use the plus (+) operator to concatenate lists:

a = [1,2,3] + [4,5]   # Result is [1,2,3,4,5]

Lists can contain any kind of Python object, including other lists, as in the following example:

a = [1,"Dave",3.14, ["Mark", 7, 9, [100,101]], 10]

Nested lists are accessed as follows:

a[1]      # Returns "Dave"
a[3][2]     # Returns 9
a[3][3][1]   # Returns 101

The program in Listing 2 illustrates a few more advanced features of lists by reading a list of numbers from a file and outputting the minimum and maximum values.

Listing 2 Advanced List Features

import sys            # Load the sys module
f = open(sys.argv[1])      # Filename on the command line
svalues = f.readlines()     # Read all lines into a list

# Convert all of the input values from strings to floats
fvalues = [float(s) for s in svalues]

# Print min and max values
print "The minimum value is ", min(fvalues)
print "The maximum value is ", max(fvalues)

The first line of this program uses the import statement to load the sys module from the Python library.

The open() method uses a filename that has been supplied as a command-line option and stored in the list sys.argv. The readlines() method reads all the input lines into a list of strings.

The expression [float(s) for s in svalues] constructs a new list by looping over all the strings in the list svalues and applying the function float() to each element. This particularly powerful method of constructing a list is known as a list comprehension.

After the input lines have been converted into a list of floating-point numbers, the built-in min() and max() functions compute the minimum and maximum values.

Closely related to lists is the tuple datatype. You create tuples by enclosing a group of values in parentheses or with a comma-separated list, like this:

a = (1,4,5,-9,10)
b = (7,)                 # Singleton (note extra ,)
person = (first_name, last_name, phone)

Sometimes Python recognizes that a tuple is intended even if the parentheses are missing:

a = 1,4,5,-9,10
b = 7,
person = first_name, last_name, phone

Tuples support most of the same operations as lists, such as indexing, slicing, and concatenation. The only difference is that you cannot modify the contents of a tuple after creation. (That is, you cannot modify individual elements, or append new elements to a tuple.)

  • + Share This
  • 🔖 Save To Your Account