Python Tutorial

Showing posts with label list comprehensions. Show all posts
Showing posts with label list comprehensions. Show all posts

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))]