Creating new lists from other iterables
List comprehensions are used for creating new lists from other iterables.
As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
This is the basic syntax:
new_list = [expression for_loop_one_or_more conditions]
For example, find the squares of a number using the for loop:
Finding squares using list comprehensions:
Here, square brackets signify that the output is a list. n**2 is the expression executed for each element and for n in numbers is used to iterate over each element. In other words, execute n**2 (expression) for each element in numbers.
A more complex example of list comprehension:
Find common numbers from two lists using for loop.
Using conditions in list comprehensions:
Find common numbers from two lists using list comprehension:
Return numbers from the list which are not equal as a tuple:
Here. as we are returning a list of tuples, tuples must be in parenthesis to avoid errors. In the above example, tuples with a and b will be printed such that a and b are not the same.
List comprehensions can also be used to iterate over strings, as shown below:
This example converts each of the string from list_a to a smaller case.
Like tuples, list comprehensions can be used to produce a list of a list, as shown below:
Here we use list_a to create square_cube_list, which is a list of list in Python containing squares and cubes of the numbers from list_a
If you enjoyed the article and want updates about my new article, please follow me on medium and on twitter @happyrupesh223
- Beginner?s guide to ReactJS
- Why Progressive Web Apps are great and how to build one
- Let?s get this ?this? once and for all
- Service Workers
- Service Workers implementation
- Virtual DOM in ReactJS
- Zip in Python
- decorators in Python
- Concatenating two lists in Python
- lambda, map and filter in Python
- List comprehensions in Python