List Comprehension in PythonCreating new lists from other iterablesRupesh MishraBlockedUnblockFollowFollowingMay 11, 2017List comprehensions are used for creating new lists from other iterables.
As list comprehensions returns 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 signifies 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 list 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.