python-lists


A list is widely used data structures in python. It’s a collection of data items separated by a comma and enclosed in square brackets. List are mutable (i.e they can be edited). Each element has an index value starting from 0.

List Example

#!/usr/bin/python
x=[1,2,3,4]
print x

y=["a,sfsdf","b","c","d"]
print y


output
----------

$ ./py
[1, 2, 3, 4]
['a,sfsdf', 'b', 'c', 'd']

Remember: Tuples are similar to lists but they are immutable  (they cannot be changed once created).

 


Tuple Example

#!/usr/bin/python
x=(1,2,3)
print x

output
--------
$ ./p
(1, 2, 3)


Accessing list

#!/usr/bin/python
x=[1,2,3,4,5,6,7]

print x[0]    ### prints first element
print x[1]    ### prints second element
print x[:3]   ### print first three elements
print x[3:]   ### ignore first three elements and print rest
print x[-1]   ### print last element


------output---------------
$ ./py
1
2
[1, 2, 3]
[4, 5, 6, 7]
7

 


Creating lists of list (matrix)

#!/usr/bin/python
x=[1,[1,2,3],5,[6,7,8,9]]
print x
print x[0]
print x[1][2]

output
-----------
$ ./p
[1, [1, 2, 3], 5, [6, 7, 8, 9]]
1
3
$ 

You can see how to create and access elements of nested lists.

 


List methods and operations

append to list

x.append(‘val’);

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]
x.append('zzz');
print x;

---output-----
$ ./p
[1, [2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C'], 'zzz']

see element got added at the end of the list. append takes only one item. you have to use ‘extend’ method to add multiple items (at the end of the list). If you try to add multiple elements they all will be added as a new list example:

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]
y=['a','x'];
x.append(y);
print x;

-------output----------
$ ./p
[1, [2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C'], ['a', 'x']]

 


insert

ex. x.insert(index,value) ### it will insert new value at a given index and shift elements to right. It is not to update rather it will replace and move existing element to right.

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]
x.insert(0,'zzz');
print x;


----output----------
$ ./p
['zzz', 1, [2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C']]

There is no way to use insert and add an element in list of list.

 


extend

x.extend([‘val1′,’val2’,…]);

example:

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]
x.extend(['aaa','bbb']);
print x;


----output-----
$ ./p
[1, [2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C'], 'aaa', 'bbb']

 


Difference between extend and append

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]
x.extend(['aaa','bbb']);
x.append(['aaa','bbb']);
print x;


-----output-------
./p
[1, [2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C'], 'aaa', 'bbb', ['aaa', 'bbb']]

 


index

x.list(‘value’) # searches for value’s index in list ‘x’, throws error if value is not found.

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C'],1]
print x.index(1)

-------output------
$ ./p
0

only the index of first occurence is returned.

 


remove

x.remove(‘value’) # removes the first occurence of value from list

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C'],1]
x.remove(1)
print x


----output------
./p
[[2, 3, 4, 5, 6], 3, 'a', ['A', 'B', 'C'], 1]

 


reverse

x.reverse() ## reverses the list, does not return anything but reverses the list object.

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C'],1]
x.reverse()
print x

------output-------
./p
[1, ['A', 'B', 'C'], 'a', 3, [2, 3, 4, 5, 6], 1]

 


sort

x.sort() ## sorts the list object (does not return anything)

#!/usr/bin/python
x=[1,[2,3,4,5,6,2],3,'a',['A','B','C'],1]
x.sort()
print x
y=['A','BXZ','BXY','AAA']
y.sort()
print y

------output------
$ ./p
[1, 1, 3, [2, 3, 4, 5, 6, 2], ['A', 'B', 'C'], 'a']
['A', 'AAA', 'BXY', 'BXZ']

 


pop

x.pop()  # removes the last element of the list and returns the removed element.

#!/usr/bin/python
x=[1,[2,3,4,5,6,2],3,'a',['A','B','C'],1]
print x.pop()
print x

------output-------
./p
1
[1, [2, 3, 4, 5, 6, 2], 3, 'a', ['A', 'B', 'C']]

 


Iterating over lists

#!/usr/bin/python
x=[1,[2,3,4,5,6,],3,'a',['A','B','C']]

for element in x:
 print element


output
-------
$ ./p
1
[2, 3, 4, 5, 6]
3
a
['A', 'B', 'C']


List Comprehension

>>> [x for x in range(1,10) if x%2==0 if x==6]
[6]
>>> [x for x in range(1,10) if x%2==0 if x==6 or x==4]
[4, 6]
>>> [x for x in range(1,10) if x%2==0 if x==6 or x==4]
[4, 6]

See above how the list is created without declaring x[] and then x.append().

 


How to clone or copy a list in python?

  • From python 3.3+ you can use the copy method. list2=list1.copy()
  • You can also use slice technique. list2=list1[:]

+ There are no comments

Add yours