Sunday, February 21, 2016

Slicing and List Comprehension in Python

Slicing in python.

This lets you work on specific portions of the given sequence(list/str/bytes). Read it as Slice a pound of bread and give half to brother and keep half for yourself.

Slicing can be extended to any Python class that implements the __getitem__ and __setitem__ special methods.

Syntax :

gucalist[start:end], where start is inclusive and end is exclusive.

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four:', a[:4])
print('Last four: ', a[-4:])
print('Middle two:', a[3:-3])

>>>
First four: ['a', 'b', 'c', 'd']
Last four:  ['e', 'f', 'g', 'h']
Middle two: ['d', 'e']


Starting from the first, zero is understood.
a[:5] = a[0:5]

Slicing till the end,   "end" is understood.

a[5:] = a[5:len(a)]

Playing with negative index

a[:]      # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[:5]     # ['a', 'b', 'c', 'd', 'e']
a[:-1]    # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a[4:]     #                     ['e', 'f', 'g', 'h']
a[-3:]    #                          ['f', 'g', 'h']
a[2:5]    #           ['c', 'd', 'e']
a[2:-1]   #           ['c', 'd', 'e', 'f', 'g']
a[-3:-1]  #                          ['f', 'g']


NOTES :
1. Slicing operation returns the whole new object.. Keeping the original as it is.
b = a[4:]
print('Before:   ', b)
b[1] = 99
print('After:    ', b)
print('No change:', a)

>>>
Before:    ['e', 'f', 'g', 'h']
After:     ['e', 99, 'g', 'h']
No change: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


List Comprehension 
===================
Compute the sqaure of each numbers in the list

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in a]
print(squares)

>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

what if you wanted only the squares of the numbers in the given list, which are divisible by 3

squares = [x**2 for x in a if x%3==0]

List comprehension for dicts

>>> g_fam= {'ravi':33, 'rash':31, 'tan':6, 'sam':1}
>>> age_dict = {age:name for name, age in g_fam.items()}
>>> print(age_dict)
{1: 'sam', 33: 'ravi', 6: 'tan', 31: 'rash'}
>>>


More than two expressions in list comprehension

Flatting the matrix into a single list

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat)

NOTE : These expressions run in the order provided from left to right. So in this case take each row first and loop over it.

Multiple loops is replicating the two-level deep layout of the input list. For example, say you want to square the value in each cell of a two-dimensional matrix. This expression is noisier because of the extra [] characters, but it’s still easy to read.

squared = [[x**2 for x in row] for row in matrix]
print(squared)

>>>
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]


multiple if conditions in a list comprehension

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = [x*x for x in a if x > 4 and x % 2 == 0] # get the squares of each if it even and greater than 4.



No comments: