ADVANCED LIST PROCESSING
List
comprehension is an elegant and concise way to create new list from an existing
list in Python.
List
comprehension consists of an expression followed by for statement inside square brackets.
Here is
an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
This code
is equivalent to
pow2 = []
for x in range(10):
pow2.append(2 ** x)
A list
comprehension can optionally contain more for or if statements. An optional if statement can
filter out items for the new list.
Here are
some examples.
>>>
pow2 = [2
** x for x in range(10) if x > 5]
>>>
pow2
[64, 128, 256, 512]
>>>
odd = [x
for x in range(20) if x % 2 == 1]
>>>
odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[x+y for x in ['Python ','C '] for y in
['Language','Programming']] ['Python Language', 'Python Programming', 'C
Language', 'C Programming']
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.