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:

names.append("Kate") 

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 ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.