List Comprehension in Python

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.

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_aOther articles:Beginner’s guide to ReactJSThe Journey of JavaScript: from Downloading Scripts to ExecutionWhy Progressive Web Apps are great and how to build oneLet’s get this ‘this’ once and for allService WorkersService Workers implementationExecution Context in JavaScriptVirtual DOM in ReactJSPrototypes in JavaScript‘this’ in JavaScriptObject.

create in JavaScriptInheritance in JavaScriptCreate objects in JavaScriptObjects in JavaScriptZip in Pythondecorators in PythonConcatenating two lists in Pythonlambda, map and filter in PythonList comprehensions in Python.

. More details

Leave a Reply