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 ...
Get Python: Essential Reference, Third 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.