34
Python Collections and Files
Python has a number of different collection objects: lists (essentially arrays), tuples, dictionaries, and sets. We look at all of them in this chapter, along with how we can read data into them from files.
We have already seen some simple examples of using Lists, the Python equivalent of arrays. You can create lists programmatically by simply declaring the contents inside square brackets.
nlist = [2, 4, 8, 16] # create list
Then you can access elements of the list by position: All lists start at index zero.
print (nlist[0]) # first element 2
You can access the final element by using an index of -1
.
print (nlist[-1]) # last ...
Get Python Programming with Design Patterns 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.