List comprehensions provide an alternative syntax to creating lists and other sequential data types.
A list comprehension creates a new list by applying an expression to each element of an iterable.
The most basic form is:
[ <expression> for <element> in <iterable> ]Example 1: Creating a List of 1 to 10 numbers Using List Comprehensions
num_list=[n for n in
range(1,11)]
print(num_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]To create a list of squared integers Using List Comprehension
square_list=[n*n for n in
range(1,11)]
print(square_list)Output:
[1, 4, 9, 16, 25, 36,
49, 64, 81, 100]
To create a list of uppercase characters from a string
print(uc_list)
Output:
To create a list of uppercase characters from a string
uc_list=[s.upper() for s in "Hello
World"]
print(uc_list)
Output:
['H', 'E', 'L', 'L',
'O', ' ', 'W', 'O', 'R', 'L', 'D']
Post a Comment