Sunday, December 27, 2009

Basics of Python List

Python List is a very useful feature. This is particularly useful for me because
  • I can keep different data types within the same list
  • Looping is very easy
  • List class has more or less all the necessary built-in functions. I know many of you might differ. Its just my personal view.

The working process of List is a bit different. Lists are actually manipulated using pointers. So we need to be careful when using Lists. Here are some interesting features of List.

Copying a List:
We might do this:

>>> lista = listb

This does not copy the listb items in lista. What happens actually is an exchange of pointers. lista now points to listb. If we change listb, list a is changed automatically. An example is:

>>> listb = [1,2,3,4,5]
>>> lista = []
>>> lista = listb
>>> lista
[1, 2, 3, 4, 5]
>>> listb.append(6)
>>> lista
[1, 2, 3, 4, 5, 6]

So how can we have a new copy of list item. I do it in two ways.

Way 1: There is an overloaded operator [:] which creates a new copy.

lista = listb[:]

Now listb and lista are two different lists.

Way 2:

There is a python library named copy

>>> from copy import copy
>>> listc = copy(lista)
>>> listc
[1, 2, 3, 4, 5, 6]

So we can have a new copy using these two ways. I'll be glad to know if someone informs me of some other useful rather easy ways of copying lists.

Dillema in Loops!!!

Sometimes it can be a dillema when we alter a list within iteration. Like the following code:

>>> lista
[1, 2, 3, 4, 5, 6]
>>> for each in lista:
... lista.remove(each)
... print lista
...
[2, 3, 4, 5, 6]
[2, 4, 5, 6]
[2, 4, 6]

Explanation:

As I said before, list operations use pointers in most cases. For an iteration through a list, the pointer just starts moving from the first element, then moves to the second element, then third in this way. In the above code we are removing an element from the list in each iteration and the list size is shortening. So the loop only iterates thrice as the pointer moves to the fourth element after third iteration but the list now holds only three elements.

Well, I discovered it much later from the time I started working with python.

If the above two topics help you in any way then my effort will be successful. Please inform me if you have any question regarding this post.

Have a nice day... :))

No comments:

Post a Comment