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


1 to 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [2]:
def square(x):
    return x*x

squares = [square(num) for num in numbers]
print squares


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

In [3]:
even_squares = [ num*num for num in numbers if (num % 2) == 0]
print even_squares


[4, 16, 36, 64, 100]

In [4]:
squares = [num*num for num in numbers]
print squares


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

In [5]:
# invalid syntax
[print num for num in numbers]


  File "<ipython-input-5-f58f43de3eb3>", line 2
    [print num for num in numbers]
         ^
SyntaxError: invalid syntax

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


['count_lines_argparse.py', 'compute_it_v1.py', 'compute_it.py', 'count_lines.py', 'split_fasta.py', 'makeblastdb.py']
[<open file 'bin/count_lines_argparse.py', mode 'r' at 0x7f7c9dc704b0>, <open file 'bin/compute_it_v1.py', mode 'r' at 0x7f7c9dc705d0>, <open file 'bin/compute_it.py', mode 'r' at 0x7f7c9dc70540>, <open file 'bin/count_lines.py', mode 'r' at 0x7f7c9dc70660>, <open file 'bin/split_fasta.py', mode 'r' at 0x7f7c9dc706f0>, <open file 'bin/makeblastdb.py', mode 'r' at 0x7f7c9dc70780>]

In [9]:
numbers = range(1,10)
sequence_generator = ( num**num for num in numbers)
print list(sequence_generator)


[1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]

In [10]:
sum_of_squares = sum([ num*num for num in numbers ])
print "sum of squares 1 to 10:", sum_of_squares


sum of squares 1 to 10: 285

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


2
4

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


<generator object <genexpr> at 0x7f7c9cf855a0>
36
64
100
144
196
256
324
400
484
576
676
784
900

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


1
4
9
16
25
36
49
64
81
100

In [31]:
print [ (num, num**2) for num in numbers][1:6]


[(2, 4), (3, 9), (4, 16), (5, 25), (6, 36)]

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]:
False

Find prime numbers using list comprehension and for loop.


In [40]:
primes = [num for num in range(100) if is_prime(num)]
print primes


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

In [42]:
primes = []
for num in range(100):
    if is_prime(num):
        primes.append(num)
print primes


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

In [ ]: