Python list comprehensions are a way of generating a list by applying a function to all (or some) elements of a collection. They are documented in the Python documentation as well as this blog and as part of this python course.
In [1]:
numbers = range(1,11)
print "1 to 10:", numbers
In [2]:
def square(x):
return x*x
squares = [square(num) for num in numbers]
print squares
In [3]:
even_squares = [ num*num for num in numbers if (num % 2) == 0]
print even_squares
In [4]:
squares = [num*num for num in numbers]
print squares
In [5]:
# invalid syntax
[print num for num in numbers]
In [8]:
import os
import os.path
list_of_files = [ filename for filename in os.listdir('bin/')
if os.path.isfile(os.path.join('bin', filename))]
print list_of_files
file_objects = [ open(os.path.join('bin',filename))
for filename in list_of_files ]
print file_objects
In [9]:
numbers = range(1,10)
sequence_generator = ( num**num for num in numbers)
print list(sequence_generator)
In [10]:
sum_of_squares = sum([ num*num for num in numbers ])
print "sum of squares 1 to 10:", sum_of_squares
In [11]:
def next_even_number():
number = 0
while True:
number += 2
yield number
In [12]:
evens_generator = next_even_number()
print evens_generator.next()
print evens_generator.next()
In [13]:
even_squares = ( num*num for num in evens_generator )
print even_squares
for square in even_squares:
if square > 1000:
break
print square
In [26]:
class Squares(object):
def __init__(self, start=0, stop=10):
self.start = start
self.stop = stop
self.current = start
def __iter__(self):
return self
def next(self):
self.current += 1
if self.current > self.stop:
raise StopIteration
else:
return self.current**2
In [28]:
squares = Squares()
for square in squares:
print square
In [31]:
print [ (num, num**2) for num in numbers][1:6]
In [36]:
def is_prime(num):
if num < 2:
return False
for other_num in range(2, int(num/2)+1):
if (num % other_num) == 0:
return False
return True
In [39]:
is_prime(0)
Out[39]:
Find prime numbers using list comprehension and for loop.
In [40]:
primes = [num for num in range(100) if is_prime(num)]
print primes
In [42]:
primes = []
for num in range(100):
if is_prime(num):
primes.append(num)
print primes
In [ ]: