Personal tools
You are here: Home CDAT Tips and Tricks Python Tips Lists and tuples in python.
Document Actions

Lists and tuples in python.

by Renata McCoy last modified 2007-05-08 10:46

Goal: Learn about lists and tuples in python.


  Lists and tuples are sequences of arbitrary objects. Lists can be created by:
mylist = ["a", 1.0, "c", 4]
Note that you can mix items of any type in a list. You can also have lists nested inside lists.
my_other_list = ["a", "b", [1,2,3], "d"]
The lists are indexed by integers starting with zero. To see the first item in mylist, you would:
firstitem = mylist[0]         # returns the item "a"

# To set an item:
mylist[2] = "x"           # Changes the item in the index position 2.
print mylist
# Output: ["a", 1.0, "x", 4]
To append new members to the list, the append() method is used as follows:
mylist.append("nextitem")
print mylist
# Output: ["a", 1.0, "x", 4, "nextitem"]
Similarly, individual items can be removed from the list using the remove() method:
mylist.remove(1.0)
print mylist
# Output: ["a", "x", 4, "nextitem"]
You can also insert items into specific positions:
mylist.insert(1, "inserted_item")
print mylist
# Output: ["a", "inserted_item", "x", 4, "nextitem"]
Lists can be concatenated by using the "+" operator:
newlist = mylist + [9, 10, 11]
print newlist
# Output: ["a", "inserted_item", "x", 4, "nextitem", 9, 10, 11]
Tuples are very similar to lists and are constructed by using parentheses instead of brackets or just a comma-separated list.
mytuple = (1, 2, -3)
myvector = (magnitude, direction)
# is the same as
myvector = magnitude, direction
Tuples support the same operations as are supported by lists except the appending or modification of elements after they are created. That is, you cannot modify elements or append elements to a tuple.

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.



Powered by Plone