HomePython Page 2 - Python 101 (part 3): A Twist In The Tail
Here Comes A Hero - Python
Find out more about adding flow control to your Python programswith the "for" and "while" loops, see how the range() function can be usedto generate number ranges, and learn all about list objects. And bring anold flame along for the ride.
For simple Python programs, this is usually more than enough. However, asyour Python programs grow in complexity, you're going to need more advanceddata structures to store and manipulate information. And that's exactlywhere lists come in.
Unlike string and number objects, which typically hold a single value, alist can best be thought of as a "container" variable, which can containone or more values. For example,
Here, "superheroes" is a list containing the values "Spiderman","Superman", "Human Torch", and "Batman".
Lists are particularly useful for grouping related values together - names,dates, phone numbers of ex-girlfriends et al. The various elements of thelist are accessed via an index number, with the first element starting atzero. So, to access the element "Superman", you would use the notation
>>> superheroes[0]
'Spiderman'
>>>
while
>>> superheroes[3]
'Batman'
>>>
- essentially, the list name followed by the index number enclosed withinsquare braces. Geeks refer to this as "zero-based indexing".
Defining a list is simple - simply assign values (enclosed in squarebraces) to a variable, as illustrated below:
>>> oldFlames = ["Jennifer", "Susan", "Tina", "Bozo The Clown"]
>>>
The rules for choosing a list name are the same as those for anyother Python variable - it must begin with a letter, and can optionally befollowed by more letters and numbers.
If you've worked with other programming languages, it should now be obviousthat lists in Python are the equivalent of arrays in Perl, PHP and C.However, unlike these languages, Python does not restrict lists to elementsof a specific object type, and can mix strings, numbers and even otherlists within a single list "container".