Course Content
What is Python?
Introduction of Python and Its setup
0/2
Control Statement
Control statements are used to control the flow of execution depending upon the specified condition/logic.
0/4
File Handling
File handling is an important component of any application. Python has multiple functions for creating, reading, updating, and deleting files.
0/2
Examples
Following are the examples of python scripts to try hands-on, you are ready to start your python journey.
0/7
Python
About Lesson

List comprehension

List comprehensions are an elegant way to create new lists in Python. List comprehension is faster and more compact than normal functions and loops for creating a list in Python.

Syntax of List Comprehension

[expression for item in list]

List Comprehension vs For Loop in Python

Suppose, we want to separate the letters of the word animal and add the letters as items of a list. The first thing that comes to mind could be using for loop.

Example 1: using for loop

letters = []

for i in 'animal':
    letters.append(i)

print(letters)

When we run the program, the output will be:

['a', 'n', 'i', 'm', 'a', 'l']

Python has an easier way to solve this issue using List Comprehension.

Example 2: using list comprehension

letters = [ letter for letter in 'animal' ]
print(letters)

In the above example, a new list is assigned to variable  letters, and the list contains the items of the iterable string ‘animal’. We call print() function to receive the output.

List comprehension is generally more compact and faster than normal functions and loops for creating lists.