Linux

Python List Tips

So far you have learned Python, In this page you will learn List tips and tricks. In Python list chapter you have learned about slicing of lists , here you will learn Python list Negative index slicing.

Python List assignment

You can assign list's values to corresponding reference using assignment operator.
>>> Robert, Chris = ["Iron-man", "Captain"]
>>> Robert
'Iron-man'
>>> Chris
'Captain'
The above, list's value assignments deserves little bit more explanation. Total number of element on left hand side of assignment operator must be equal to length of the list.

Python list Negative index slicing

>>> list1 = [0,1,2,3,4,5,6,7,8,9,10,11,12]
>>> list1[-5:-1]
[8, 9, 10, 11]
>>> list1[-1:-5]
[]
Python negative indexing goes left to right that's why listslist1[-1:-5] prints nothing.

Python List slicing with steps

Syntax
list[start:end:step]
It include steps mentioned in last arguments, let us check with example.
>>> list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[0:9:2]
[0, 2, 4, 6, 8]
>>> list1[::3]
[0, 3, 6, 9]
You can see that when you did not specify the start and end arguments, it takes defaults values. Here is very good trick to reverse the list. Use negative step.
>>> list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> list1[::-2]
[10, 8, 6, 4, 2, 0]

If you provide value to start and end argument then it would return empty list.

Python List slice addition

In this section we will study how to extent and extend + reassign the value
>>> list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[4:5] = [90, 80]
>>> list1
[0, 1, 2, 3, 90, 80, 5, 6, 7, 8, 9, 10]

In above example you can see that list1[4] i.e 4 is replaced by 40 and list[5] place is taken by 50. Consider one more example of list extend by slicing assigment.
>>> list1[8:8] = [67,80,45]
>>> list1
[0, 1, 2, 3, 90, 80, 5, 6, 67, 80, 45, 7, 8, 9, 10]

You can see not one element is replace just shifting took place.

Python Lists Zip and Unzip

Consider you want to make pair of elements of different lists. Use Zip to make pairs
>>> list1 = ['a','b','c']
>>> list2 = [1,2,3]
>>> z = zip(list1,list2)
>>> z
[('a', 1), ('b', 2), ('c', 3)]

You can see the pairs Lets unzip it.
>>> zip(*z)
[('a', 'b', 'c'), (1, 2, 3)]

Lets zip two Python lists with different length.
>>> list3 = ['x','y']
>>> z = zip(list1, list3)
>>> z
[('a', 'x'), ('b', 'y')]

The zip function takes length of shortest list.

iter()

>>> list1 = ['a','b','c']
>>> x = iter(list1)
>>> x.next()
'a'
>>> x.next()
'b'
>>> x.next()
'c'
>>> x.next()
Traceback (most recent call last):
File "", line 1, in
x.next()
StopIteration

You can see that iter() function take list list1 and next() function extracts element one by one as we demanded.

sum(iterable[, start])

In simple words, if you want sum of numbers of Python list, then use sum function. Default value of start is 0. If argument start is present then it would be add in sum of list's number.
>>> k = [1,2,3,4,5,6]
>>> sum(k)
21
>>> sum(k,2)
'23'
>>> j = ['a',1,2,3,4]
>>> sum(j)
Traceback (most recent call last):
File "", line 1, in
sum(j)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Error shows that list's value should be int. How sum() function works. It works like, k[0]+k[1]+k[2].... upto length of list.
Consider you have a list like [[1, 2], [3, 4], [5, 6]] and you want to make list flat, like [1,2,3,4,5,6]. See the example below.
>>> list1 = [[1, 2], [3, 4], [5, 6]]
>>> sum(list1, [])
[1, 2, 3, 4, 5, 6]

I hope, you understood the example for better understanding it works like list1[0]+list[1]+list[2]+[] which makes [1, 2]+[3, 4]+[5, 6]+[]
>>> list2 = ['a','b']
>>> sum(list1,list2)
['a', 'b', 1, 2, 3, 4, 5, 6]
In above example list1's element would be added with list2.

Flattening Python lists by for loop

There is another techniques to flat the lists. Let us discuss with the example.
>>> list1 = [[1, 2], [3, 4], [5, 6]]
>>> [e for sublist in list1 for e in sublist]
[1, 2, 3, 4, 5, 6]
In above example you can see that two for loops are there, onefor loop for outer list and one for loop for inner lists. and Printing value is e. If you still have doubt look next example.
>>> list2 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> [e for sublist1 in list2 for sublist2 in sublist1 for e in sublist2]
[1, 2, 3, 4, 5, 6, 7, 8]
In above example three lists are there, therefore we used three for loops.

Python List with itertools

Itertools module provides a set of functions, fast and memory efficient, for working with iterable sequence. Here we will discuss some important function for Python lists.

Chain()

The function chain takes multiple iterable like list, tuple, dictionary as an arguments and return single sequence.
from itertools import *
for each in chain(['x','y','z'],['a','b','c']):
    print each,
Out-put : x y z a b c
You can see that it return single sequence.
Now check list and tuple.
from itertools import *
for each in chain(['x','y','z'],('a','b','c')):
    print each,
Out-put : x y z a b c
for users. try list with dictionary.

Python list Interviews problems

Let us discuss some interview related problem.

Problem 1

  1. list1 = [ [ ] ] * 5
  2. list1 # output?
  3. list1[0].append(10)
  4. list1 # output?
  5. list1[1].append(20)
  6. list1 # output?
  7. list1.append(30)
  8. list1 # output?

Problem 2

def extendList(val, list_new=[]):
    list_new.append(val)
    return list_new
list1 = extendList(10)
list2 = extendList(123)
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Out-put : ??


Problem 3

def extendList(val, list_new=[]):
    list_new.append(val)
    return list_new
list1 = extendList(10)
list2 = extendList(123, [])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Out-put : ??






admin