Python: Sequences

A sequence is a special data structure in Python where data elements can be referenced thru numbers, an index so to speak.
Python knows 6 different types of sequences, the three most important ones are:

  • strings
  • lists
  • tuples

A string is a list of characters, like "Hello World!". A list is simply a list of any sort of data element, in many other programming languages known as array. A tuple is like a list, but not changeable.
For all three we use square brackets to access data elements:

>>> s = "Hello World!"
>>> l = [1,2,3]
>>> t = (1,2,3)
>>> s'Hello World!'
>>> l[1, 2, 3]
>>> t(1, 2, 3)
>>> s[1]'e'
>>> l[1]2
>>> t[1]2

It is important to be aware of the fact that indexing always start with 0, thus the first data element has index 0.

This indexing technique we can also use to change values, but not for tuples, and not for strings as well:

>>> s[1] = 'a'
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 
'str' object does not support item assignment
>>> l[1] = 4
>>> l[1, 4, 3]
>>> t[1] = 4
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 
'tuple' object does not support item assignment

Besides simple indexing sequences allow

  • slicing ( obtaining some part of the sequence )
  • adding
  • multiplying
  • testing membership
  • determining length, min, max

lists as a special form of a changeable sequences allow even more of course, like

  • changing single elements
  • deleting single elements
  • appending
  • extending
  • inserting
  • finding an index
  • removing
  • reversing
  • sorting
  • counting

lists don’t need to contain data elements of the same data type, thus the following is a valid list as well containing two numbers and one string:

>>> l = (1, "two", 3)
>>> l(1, 'two', 3)
>>> l[1]'two'

Things can get even more complex: data elements actually can be data structures:

>>> l = (1, (2, "two", "zwei"), 3)
>>> l[1](2, 'two', 'zwei')
>>> l[1][1]'two'

We can use my Python Expression Evaluator to try out a view of those expressions, like e.g. (1, "two", 3)[1]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: