Python - Using List Comprehensions

Introduction

To use range to change a list as we step across it:

Demo

L = [1, 2, 3, 4, 5] 

for i in range(len(L)): 
    L[i] += 10 # www  .  j a v a2  s  . c  o  m
print( L )

Result

The list comprehension expression makes many such coding patterns obsolete.

We can replace the loop with a single expression that produces the desired result list:

Demo

L = [1, 2, 3, 4, 5] 

L = [x + 10 for x in L] 
print( L )#   ww w. j a va 2  s  .  co  m

Result

A list comprehension looks like a backward for loop.

Syntax

List comprehensions are written in square brackets.

They begin with an arbitrary expression that we make up, for example x + 10.

Python executes an iteration across L inside the interpreter, assigning x to each item in turn.

Then Python collects the results.

The result list we get back is a new list containing x + 10, for every x in L.

In fact, this is exactly what the list comprehension does internally.

res = [] 
for x in L: 
     res.append(x + 10) 
print( res )

Related Example