Python List Comprehension

The python list and list compression features are two of the language’s most significant characteristics, which can be used to build powerful functionality with just one line of code.

It’s a beautiful technique to make lists without using the for-loop construct. List comprehension allows you to generate a new list with just one line of code, making Python scripts easier to read and maintain.

Rather than constructing an empty list and adding each element at the end, we could use list comprehension to initialize the list and its content in the same statement.

Syntax :

[ expression for item in a list {if condition_is_met} ]

List comprehension is defined inside square brackets [ ]. This reminds us that the resulting object is definitely a list.

a) An expression is defined inside the brackets. This is a statement that returns a specific value for each item in a list that already exists.

b) We define the sequence we wish to iterate through with the code for item in a list To filter elements from an existing list,

c) we can use an if conditional statement inside the brackets.

Example : Reverse String using for loop

def revString(strlist):
    li = []
    for i in strlist:
        li.append(i[::-1])
    return  li

inp = ['code','in','pocket']
print(revString(inp))
Output : ['edoc', 'ni', 'tekcop']

In above example we create a reverse string list using for loop, in which we have to create a blank list after reverse string need to append into that new list then return that new list. This process take a multiple lines of code so reducing complexity of code we use list compression.

Example : Reverse String using list compression

inp = ['code','in','pocket']
res = [i[::-1] for i in inp]
print(res)
Output : ['edoc', 'ni', 'tekcop']

Nested List Comprehensions

Nested List Comprehensions are similar to nested for loops in that they are a list comprehension within another list comprehension. The programme that implements nested loop is as follows:

Example : Simple Nested loop

block = []
for i in range(3):
    subblock = []
    for j in range(1,4):
        subblock.append(j)
    block.append(subblock)

#print block list
print(block)
Output : [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Now by using nested list comprehensions same output can be generated in fewer lines of code.

Example : Nested List comprehensions

block = [ [ j for j in range(1,4) ] for i in range(3) ]

#print block list
print(block)
Output : [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

List Comprehensions and Lambda

Shorthand representations of Python functions are known as Lambda Expressions. When you combine list comprehensions with lambda, you get a powerful combo.

Example : Print square of numbers using list comprehension

series = [ i*i for i in range(1,5)]
print(series)
Output : [1, 4, 9, 16]

In above example we print a simple list of square each elements, now same thing we create with lambda function.

Example : Print square of numbers using lambda function

series = map( lambda x : x*x, [i for i in range(1,5)] )

print(series) # print map object
print(list(series)) # print list
Output : 
<map object at 0x000001E492D9ECE0>
[1, 4, 9, 16]

Advantages of List Comprehension

  • More time-efficient and space-efficient than loops.
  • Require fewer lines of code.
  • Transforms iterative statement into a formula.

That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Python List Comprehension

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top