Python language basics 16: array sequences
May 30, 2015 Leave a comment
Introduction
In the previous post we looked at some additional features of strings. We saw how the string constructor could be used to convert a certain type, like an integer, into a string. We also discussed how to access individual characters within a string using square brackets. Finally we looked into a couple of useful functions related to strings.
Sequences are collections of data in a container. Collections are very important facets of all mainstream programming languages. There are many different types of collections but as this is an intro course we’ll start with the easiest type of collection: the array. Arrays are also called lists.
Lists
A list collection is a list of elements in a container. This is how we construct an empty list in Python:
myFirstList = []
You can also declare a list by inserting one or more elements within the square brackets. The following list will only contain strings:
myFirstList = ["small", "medium", "large", "x-large"]
You can also insert objects of different type in the list. Here we’ll mix strings with integers and booleans:
myFirstList = ["small", 7, "medium", 8, "large", True, "x-large", False]
Lists also have a number of useful built-in functions. The “append” function allows you to add new elements to a list:
myFirstList = [] myFirstList.append("small") myFirstList.append("medium") myFirstList.append("large")
You can also easily clear a list so that it becomes empty:
myFirstList.clear()
…or reverse it so that the first element becomes last and vice versa:
myFirstList.reverse()
Accessing individual elements
Recall from the previous post how we used the square brackets to retrieve a single character from a string. A string is also a list, that is a list of characters. Therefore we can use the square brackets to access a single element in myFirstList. Keep in mind that list enumeration is zero based, i.e. the first element is element #0, the second element is element #1 and so on:
firstElement = myFirstList[0] secondElement = myFirstList[1]
We’ll look at another popular collection type in the next post: dictionaries.
Read all Python-related posts on this blog here.