Tuesday, August 11, 2009

Python lists

Here are some methods which can be used with lists in Python

We will first create a list to represent a bag of flowers:

flowers = ['rock banana', 'swollen finger grass', 'velvet leaf', 'turmeric', 'rock banana']

Let's first determine how many rock banana flowers we have in the list:

>>>flowers.count('rock banana')
2

At what index in the list does 'swollen finger grass' appear?

>>>flowers.index('swollen finger grass')
1

Let's insert a rose in there at index 2
>>>flowers.insert(2, 'rose')
>>>print flowers
['rock banana', 'swollen finger grass', 'rose', 'velvet leaf', 'turmeric', 'rock banana']

Let's say we want to delete the rose
>>>flowers.pop(2)
rose
Notice that the pop() method returns the element. If we just want to delete without returning the element, then we can use the del() built-in function in Python. I have discussed built-in functions in this blog post.

What if we want to remove an element by name. Let's remove 'swollen finger grass' using the remove() method.

>>> flowers.remove('swollen finger grass')
>>> print flowers
['rock banana', 'velvet leaf', 'turmeric', 'rock banana']

We have already spoken about slicing in the blog post on sequences. There are a few more things we can do with slicing, like replacing elements, and removing them as well.

Let's create a simple list of numbers:
numbers = [3, 5, 4, 7, 4]

Let's insert a number at the 3rd position in the list
>>>numbers[2:2] = [10]
>>>print numbers
[3, 5, 10, 4, 7, 4]
Notice that when we use slicing to assign insert into a list, we have to use an iterable for the value we insert. This is the reason we use [10] and not 10

Let's replace some elements of the list
>>> print numbers
[3, 5, 10, 4, 7, 4]
>>> numbers[3:5] = [14, 17]
>>> print numbers
[3, 5, 10, 14, 17, 4]

Let's delete the 4th element from th list
>>> numbers[3:4] = []
>>> print numbers
[3, 5, 10, 17, 4]

No comments: