Skip to content Skip to sidebar Skip to footer

Python Lists Comprehension

string = 'Hello 12345 World' numbers = [x for x in string if x.isdigit()] print numbers >> ['1', '2', '3', '4', '5'] Another example: >>> noprimes = [j for i in ra

Solution 1:

These constructs are called list comprehension.

Simple example

[x for x in iterable] literally means "for every element in iterable, add that element to newly created list" and is equivalent to

new_list = []
for x in iterable:
    new_list.append(x)

Line-by-line explanation:

Loop                             List comprehension
--------------------------------------------------------------------------
new_list = []                    [x for x in iterable]
for x in iterable:               [x for x in iterable]
    new_list.append(x)           [x for x in iterable]

A bit more complex example

[int(x) for x in string if x.isdigit()] can be read as "for every element in iterable, add the result of applying int to the element to newly created list if x.isdigit()".

Line-by-line explanation:

Loop                             List comprehension
-------------------------------------------------------------------------
numbers = []                     [int(x) for x in string if x.isdigit()]
for x in string:                 [int(x) for x in string if x.isdigit()]
    if x.isdigit():              [int(x) for x in string if x.isdigit()]
        numbers.append(int(x))   [int(x) for x in string if x.isdigit()]

Solution 2:

numbers = [x for x in string if x.isdigit()] means itemize each x in string if x is a digit

It translates to

   numbers = []
    for x in string:
        if x.isdigit()
           numbers.append(x)

Solution 3:

it's called a list comprehension, which is used to build a list using an expression instead of more than 3 statements.

numbers = [x for x in string if x.isdigit()]

is equivalent to the following:

numbers = []
for x in string:
    if x.isdigit():
        numbers.append(x)

then

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

is equivalent to the following:

noprimes = []
for i in range(2, 8): 
    for j in range(i*2, 50, i):
        noprimes.append(j)

and

primes = [x for x in range(2, 50) if x not in noprimes]

is equivalent to the following:

primes = []
for x in range(2, 50):
    if x not in noprimes
        primes.append(x)

but written as a one liner.


N.B.: You can also build a generator:

(x for x in range(0, 10))

a set:

{x for x in range(0, 10)}

and a dictionary:

{(x, x) for x in range(0, 10)}

Solution 4:

numbers = [x for x in string if x.isdigit()]

The list comprehension above is similar to the following traditional code:

numbers = []

for x in string:
    if x.isdigit():
        numbers.append(x)

Post a Comment for "Python Lists Comprehension"