Python 101 (part 3): A Twist In The Tail - Making Friends And Influencing People
(Page 3 of 8 )
Lists can be concatenated with the + operator,
>>> oldFlames = ["Jennifer", "Susan", "Tina", "Bozo The Clown"]
>>> superheroes = ["Spiderman", "Superman", "Human Torch", "Batman"]
>>> strangeFriends = oldFlames + superheroes
>>> strangeFriends
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown', 'Spiderman', 'Superman',
'Human Torch', 'Batman']
>>>
and repeated with the * operator, in much the same manner as strings andnumbers.
>>> oldFlames * 3
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown', 'Jennifer', 'Susan',
'Tina', 'Bozo The Clown', 'Jennifer', 'Susan', 'Tina', 'Bozo The Clown']
>>>
"Slices" of a list can be extracted using notation similar to that used forextracting substrings - take a look:
>>> oldFlames
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown']
>>> oldFlames[0]
'Jennifer'
>>> oldFlames[0:2]
['Jennifer', 'Susan']
>>> oldFlames[0:5]
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown']
>>> oldFlames[0:]
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown']
>>> oldFlames[:3]
['Jennifer', 'Susan', 'Tina']
>>> oldFlames[-4]
'Jennifer'
>>> oldFlames[-1]
'Bozo The Clown'
>>>
The built-in len() function can be used to calculate the number of elementsin a list,
>>> superheroes
['Spiderman', 'Superman', 'Human Torch', 'Batman']
>>> len(superheroes)
4
>>>
while the "in" and "not in" operators can be used to test for the presenceof a particular element in a list. A match returns 1 (true), while afailure returns 0 (false).
>>> superheroes
['Spiderman', 'Superman', 'Human Torch', 'Batman']
>>> "batman" in superheroes
0
>>> "Batman" in superheroes
1
>>> "Batma" in superheroes
0
>>> "Incredible Hulk" in superheroes
0
>>> "Incredible Hulk" not in superheroes
1
>>>
Next: We Don't Need Another Hero >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire