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:
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'e' >>> l2 >>> t2 >>>
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 = 'a' Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment >>> l = 4 >>> l[1, 4, 3] >>> t = 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 )
- 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
- finding an index
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'two' >>>
Things can get even more complex: data elements actually can be data structures:
>>> l = (1, (2, "two", "zwei"), 3) >>> l(2, 'two', 'zwei') >>> l'two' >>>