List Comprehension in Python

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

Other articles:

  1. Beginner?s guide to ReactJS
  2. The Journey of JavaScript: from Downloading Scripts to Execution
  3. Why Progressive Web Apps are great and how to build one
  4. Let?s get this ?this? once and for all
  5. Service Workers
  6. Service Workers implementation
  7. Execution Context in JavaScript
  8. Virtual DOM in ReactJS
  9. Prototypes in JavaScript
  10. ?this? in JavaScript
  11. Object.create in JavaScript
  12. Inheritance in JavaScript
  13. Create objects in JavaScript
  14. Objects in JavaScript
  15. Zip in Python
  16. decorators in Python
  17. Concatenating two lists in Python
  18. lambda, map and filter in Python
  19. List comprehensions in Python
17