×

List Comprehension in Python3

List

A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the same datatype. Therefore, a list that contains the same datatype variables is called homogenous lists, and those with different variable datatype are called heterogeneous lists.

Characteristics of a list

  1. Ordered: List stores all the elements in order.
  2. Mutable: List can be changed, i.e., elements can be added or deleted.
  3. Allows Duplicate: List allows using the duplicated item.
  4. Allows None: List allows having ‘None’ as an element.

Example

#creating a new empty list

colors = []

#adding elements at the initialization

colors = [ ‘White’, ‘Black’, ‘Red’,  ‘Green’, ‘Blue’]

In the above code, we created a new list. A list can be initialized using [], and elements may be added later. We can also add all elements at the initialization as shown in the code.

#checking type

print(type(colors))

Output:

<class ‘list’>

#printing all elements of the list

for items in colors:

            print(item, end= ‘ ’)

Output:

White Black Red Green Blue

What is List Comprehension in Python?

List comprehension is a technique that allows one to use/create a list in a single line of code.

Why do we use list comprehension?

Let’s consider a list of colors i.e.

colors = [ ‘White’, ‘Black’, ‘Red’,  ‘Green’, ‘Blue’].

We want to create a new list of all the colors with ‘e’ in their name.

Let’s try to do it without using list comprehension.

Code:

colors = [‘White’, ‘Black’, ‘Red’,  ‘Green’, ‘Blue’]

#creating a new empty list

#it will store the elements

newlist = []

for item in colors:

            if “e” in item:             #checking colors with ‘e’  in their name

                        newlist.append(item)

print(newlist)

Output:

[‘White’, ‘Red’,  ‘Green’, ‘Blue’]

Explanation:

  1. We created a new list, being used further in the code to hold the values.
  2. Using for loop to iterate over all the elements of the main list, i.e., colors.
  3. Using if-else condition to evaluate whether the item consists of ‘e’ in them.
  4. Appending the values to the new list.
  5. Finally, printing the new list to check if the code worked properly.

Using list comprehension, we can do it in fewer lines of code. We will create the new list in one line of code.

Code:

colors = [‘White’, ‘Black’, ‘Red’,  ‘Green’, ‘Blue’]

#Using line comprehension

newlist = [x for x in colors if "e" in x]

print(newlist)

Output:

[‘White’, ‘Red’,  ‘Green’, ‘Blue’]

Explanation:

  1. The same list of colors is used.
  2. The ‘newlist’ is declared and initiated in the same line.
  3. x for x in colors if "e" in x  can be divided in three parts, outcome-loop-condition.
  4. First, a loop is initiated for all items in color, i.e., for x in colors.
  5. Secondly, an if-else statement checks for the condition to be true, i.e., if "e" in x.  
  6. Finally, the outcome of the statement ‘x’ is yielded as output.
  7. Since the outcome is directly appended to the list, a new list is created with just a single line of code.

Now, we can clearly define the concept of line comprehension on our own.

Syntax of line comprehension

newlist = [expression for item in iterable if condition == True]

An expression denotes the outcome that will be stored in the newlist. It may also hold a simple code to change the outcome that comes out of for loop.

The iterable part takes in an iterable object as input. It may be a list, tuple, set, etc.

The condition part always looks for the items that yield True.

Let’s take another example to better understand the concept:

Code:

#creating a list

in = [‘J’, ‘A’, ‘V’, ‘A’, ‘T’, ‘P’, ‘O’, ‘I’, ‘N’, ‘T’]

#using line comprehension to get all letter that are not ‘A’

out = [ letter for letter in nm if letter!= ‘A’]

#printing the new list ‘out’

print(“out”)

Output:

[‘J’, ‘V’, ‘T’, ‘P’, ‘O’, ‘I’, ‘N’, ‘T’]

Explanation:

Firstly, an iterable (list in this case) 'in' is fed to for loop. Then, the condition checks for the letters that are not 'A'. Finally, all the letters except 'A' come out as output. The new list stores the entire outcome. The print statement prints the new list.

We can also use range() function as iterable during line comprehension

#using range() in list comprehension

num = [x for x in range(10) if x < 5]

#printing the new list ‘num’

print(“num”)

Output:

[‘1’, ‘2’, ‘3’, ‘4’]

Explanation:

As we know, there are three things in a line comprehension, expression, iteration, and condition.

In this example, the range(10) is iterable. The condition 'x<5' checks for 'True' as an outcome. As soon as x becomes equal to 5, the condition starts yielding 'False'. The outcome is then stored as elements inside the list.

The expression part of the list comprehension can be used to manipulate the final output to the list.

#using range() in list comprehension

num = [x+1 for x in range(10) if x < 5]

#printing the new list ‘num’

print(“num”)

Output:

[‘2’, ‘3’, ‘4’, ‘5’]

Explanation:

The expression part adds one to the outcome of the loop. Therefore, the final numbers in the list are changed. We can use a lot of other expressions instead of a simple addition operation. The expression part thus can be very useful to write better code.

FAQs about line comprehension

1. Can line comprehension be done without the condition part?

Solution: Yes, line comprehension does not require condition part in all cases. Line comprehension can be done without it but in most cases it is useful. For Example:

Code:

#list comprehension without condition part

num = [x for x in range(5)]

#printing the list

print(num)

Output:

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

2. Why should we use list comprehension?

Solution: There are numerous advantages of using a list:

1) Less coding: We need to write a single line of code instead of 2-4 lines.

2) Save time: Since less code is to be written, it saves a lot of time.

3) Eliminate function use: Sometimes, we require an external function to create a new list. Line comprehension eliminates the need to create such functions.

3. Are there any disadvantages of using list comprehension?

Solution: There are no disadvantages as such, but it sometimes makes code hard to read. If something goes wrong, it is hard to detect.


Related Topics

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.