Unlike strings, lists are "mutable", which means that the elementscontained within a list can be changed at will. For example, any listelement can be altered simply by assigning a new value to it via its index.
>>> superheroes
['Spiderman', 'Superman', 'Human Torch', 'Batman']
>>> superheroes[3] = "Captain America"
>>> superheroes
['Spiderman', 'Superman', 'Human Torch', 'Captain America']
>>>
You can alter more than one value at a time by using list slices.
>>> superheroes
['Spiderman', 'Superman', 'Human Torch', 'Captain America']
>>> superheroes[0:2] = ["Incredible Hulk", "Green Lantern"]
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America']
>>>
The built-in append() method makes it easy to add items to a list,
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America']
>>> superheroes.append("Spawn")
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America',
'Spawn']
>>>
while the del() method makes it just as easy to remove them.
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America',
'Spawn']
>>> del superheroes[4]
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America']
>>> del superheroes[0:2]
>>> superheroes
['Human Torch', 'Captain America']
>>>
Note that there's also a remove() method, which allows you to remove anelement by value rather than index.
>>> superheroes
['Incredible Hulk', 'Green Lantern', 'Human Torch', 'Captain America']
>>> superheroes.remove("Green Lantern")
>>> superheroes.remove("Captain America")
>>> superheroes
['Incredible Hulk', 'Human Torch']
>>>
Finally, the sort() and reverse() methods allow you to rearrange thecontents of a list.
>>> oldFlames
['Jennifer', 'Susan', 'Tina', 'Bozo The Clown']
>>> oldFlames.sort()
>>> oldFlames
['Bozo The Clown', 'Jennifer', 'Susan', 'Tina']
>>> oldFlames.reverse()
>>> oldFlames
['Tina', 'Susan', 'Jennifer', 'Bozo The Clown']
>>>
A number of other list methods are also available - take a look at thePython Library Reference at
http://www.python.org/doc/current/lib/lib.html for more information and examples.
Let's move on to loops.
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by