Friday, 16 January 2015

Basic List Operations


Range is a builtin function which given list as an output from the first parameter to the before numb of last parameter

List 'a' is assigned from 0-9

>>> a = range(0,10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Len 

Len is a function used to return the length of the 'a' list
>>> len(a)
10

Concatenation in lists

When two lists are added then the list grows in size to a single list

>>> b = range(11,20)
>>> b
[11, 12, 13, 14, 15, 16, 17, 18, 19]

Here 'c' is an addition of two lists
>>> c = a+b
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Equal operation in lists


In python when a list is assigned to another, it doesnt create a new list, instead it just creates a reference to the old one.
So any modification happening to the main list also effects in the assigned list
List 'c' is assigned to 'a'
>>> c=a
An element with index 9 has been deleted in the list 'a', and u can see it is not even seen in the list 'c'
>>> del(a[9])
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Repetition in lists

To repeat the same values in the list 'n' number of times, simply say list*n
>>> d = range(0,4)
>>> d
[0, 1, 2, 3]
>>> d*3
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

IN in lists

In is generally used to find whether the value is present in the list or not.
It simply returns true or false depending upon the presence of the element in list
>>> d
[0, 1, 2, 3]
>>> 4 in d
False
>>> 3 in d
True

IN used in For loop

For printing or using all the values in the list you can simply use the IN as shown below
>>> for i in d:
print i

0
1
2
3
>>> 

No comments:

Post a Comment