Programming & Scripting Tutorials

Python: Sequences and Lists



Sequences are often useful to contain lots of similar data - exam results for example.
To make a sequence in Python we simple create a variable and give it all of the elements in the list. For example if I wanted a sequence called "friends" that held name of friends, I might do it like this:

friends = ['Bob', 'Charlie', 'Bill', 'Ed']

In this case our friends sequence would contain four strings with then names "Bob", "Charlie", "Bill", and "Ed".
Python automatically numbers the sequence elements for us, but it isn't just simply 1, 2, 3, 4 - instead Python counts from zero. This makes "Bob" 0, "Charlie" 1, "Bill" 2, and "Ed" 3.
We can refer to the different elements of the sequence by referring to their number, for example to get "Charlie" I would run:

friends[1]

You'll see that running this outputs "Charlie" as expected.
Also for long sequences we can count from the back of the sequence, we do this using negative numbers - however remember we cannot have -0 as it's the same as 0.
For example to refer to Bill I would run:

friends[-2]

As "Bill" is the second to last element in the sequence.

You can also refer to strings with square brackets to get "elements" of the string (letters) - this is because strings are simply sequences of chars (characters).
For example if I wanted to output the 2nd letter of "Joe" I would run:

'Joe'[1]


This Python tutorial was written by


Back to Python

Advertisement: