FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

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:
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:

Code:

>>> 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:

Code:

>>> 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:

Code:

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


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

Code:

>>> 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]



0 blog comments below




FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.