Skill - List Comprehensions in python
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Lists in python
- Create sequences with range function in python
- ‘for’ loop in python
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
List Comprehension can be used to create a list from another list/sequence in a user-friendly way and with less lines of code.
Generally people use list comprehensions write simple for loops in a single line
All List comprehensions can be replaced by a for
loop.
But all for
loops can’t be replaced by List comprehensions.
Creating list from another sequence/list using list comprehension
- As shown in the above image, for creating a new list we require the input list, operation on each list item, conditional statement for including the list item if any.
- The conditional statement can be used as a
filter
to exclude undesired list items from the output list
Creating a list of 15 numbers using ‘List Comprehension’
lst = [t for t in range(15)]
print(lst)
# This will print
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Creating a list of 15 numbers using ‘for’ loop
lst = []
for t in range(15):
lst.append(t)
print(lst)
# This will print
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
You can see from the above two examples that list comprehension is more user friendly to write and uses less lines of code
Converting all strings in list to uppercase
cities = ['Mumbai', 'Delhi', 'Bangalore ', 'Hyderabad',
'Ahmedabad', 'Chennai', 'Kolkata',
'Surat', 'Pune']
lst = [x.upper() for x in cities]
print(lst)
Using the conditional statement as filter in list comprehension
In this example we will generate even numbers using list comprehension
lst = [x for x in range(0,17) if x%2==0]
print(lst)
# this will print
# [0, 2, 4, 6, 8, 10, 12, 14, 16]
Video
Video for this post can be found here
Online Interpreter
You can run these codes online at https://www.programiz.com/python-programming/online-compiler/
Comments
Post a Comment