List Comprehension
Table of contents:
- Simple List Comprehension
- Adding Condition
- Adding if… else… statement
- Nested ifs in list comprehension
List Comprehension
List comprehensions provide a concise way to create lists. It is frequently used to make new lists where every element is the result of some operations applied to anthor iterable object.
Simple List Comprehension
Create a list and square the number from 0 to 9:
For Loop Method:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List Comprehension Method:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Adding Condition
Square the number from 0 to 9, and store the odd number to a list:
For Loop Method:
[1, 9, 25, 49, 81]
List Comprehension Method:
- The
if
statement is put at the end
[1, 9, 25, 49, 81]
Adding if... else... Statement
Square the number from 0 to 9 and plus 1 for each of number. Then, create a list to store a list of strings.When the number is an odd number, store ‘odd’. Otherwise, store ‘even’.
For Loop Method:
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
List Comprehension Method:
The position of if
statement has been moved to front and followed by the else statement
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
Nested ifs in list comprehension
1. Two ifs
For Loop Method:
[5, 65]
List Comprehension Method:
[5, 65]
2. Ifs and else with three outputs
For Loop Method:
['odd',
'false',
'odd',
'odd and True',
'odd',
'false',
'odd',
'odd and True',
'odd',
'false']
List Comprehension Method:
['odd',
'false',
'odd',
'odd and True',
'odd',
'false',
'odd',
'odd and True',
'odd',
'false']