Python List Comprehension and Slicing
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create list in python. We can create lists just
like mathematical statements and in one line only. The syntax of list comprehension is easier to
grasp.
Output expression,
input sequence,
For example :
x is variable and
if x % 2 == 1 is predicate part.
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Extracted digits
Multiplication Table
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
After getting the list, we can get a part of it using python’s slicing operator which
has following syntax :
[start : stop : steps]
So [: stop] will slice list from starting till stop index and [start : ] will slice list from
start index till end Negative value of steps shows right to left traversal instead of
left to right traversal that is why [: : -1] prints list in reverse order.
# Let us first create a list to demonstrate slicing
# lst contains all number from 1 to 10
lst = range(1, 11)
print lst
# below list has numbers from 2 to 5
lst1_5 = lst[1 : 5]
print lst1_5
# below list has numbers from 6 to 8
lst5_8 = lst[5 : 8]
print lst5_8
# below list has numbers from 2 to 10
lst1_ = lst[1 : ]
print lst1_
# below list has numbers from 1 to 5
lst_5 = lst[: 5]
print lst_5
# below list has numbers from 2 to 8 in step 2
lst1_8_2 = lst[1 : 8 : 2]
print lst1_8_2
# below list has numbers from 10 to 1
lst_rev = lst[ : : -1]
print lst_rev
# below list has numbers from 10 to 6 in step 2
lst_rev_9_5_2 = lst[9 : 4 : -2]
print lst_rev_9_5_2
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 3, 4, 5]
[6, 7, 8]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
[2, 4, 6, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 8, 6]
Output:
[25]
100