Python Tutorial

Friday, December 20, 2013

Python list comprehensions

Python list comprehensions provide many way to create list.
The comrehensions format is [*transform* *iteration* *filter* ].
Let's have some example.

# read a file line by line check whether or not "word" contains in each line (ignore case)
print [ line.strip("\n").lower() for line in open("a.in") if "word" in line]

# initialize array by square number
print [i**2 for i in range(10)]
# initialize array with tuples 
print [(i,i**2) for i in range(10)]

# initialize array by odd number
print [i for i in range(10) if i%2]

words = ["Life", "is", "very", "easy", "Python"]
# print first character of each word
print [word[0] for word in words]

# make all words to upper case
print [word.upper() for word in words]

# Sum each element of two array
a = [1, 2, 3]
b = [4, 5, 6]
print [a[i]+b[i] for i in range(len(a))]

1 comments:

Abu Zahed Jony said...

import math

N = 100
r = int(math.ceil(math.sqrt(float(N))))

primes = [x for x in range(2, N) if x not in [j for i in range(2, r) for j in range(i*2, N, i)]]

# prime generate using list comprehension
# It is not optimize code, Do not try with large value of N,
# N within 1000 is ok.

Post a Comment