To use range to change a list as we step across it:
L = [1, 2, 3, 4, 5] for i in range(len(L)): L[i] += 10 # w ww .j ava2 s.co m print( L )
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:
L = [1, 2, 3, 4, 5] L = [x + 10 for x in L] print( L )# from w ww . j av a2 s . c o m
A list comprehension looks like a backward for loop.
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 )