O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lists

Lists 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"

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

names.append("Kate")

To insert an item in 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:

 b = names[0:2] # Returns [ "Jeff", "Mark" ] c = names[2:] # Returns [ "Sydney", "Ann", "Phil", "Kate" ] names[1] = 'Jeff' # Replace the 2nd ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required