×

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

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Loan Calculator using PyQt5 in Python

In the following tutorial, we will learn how to build a Loan Calculator application using the PyQt5 library in the Python programming language. So, let's get started. Introduction to the code: The heading...

4 minutes read.

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

EDA in Python

The EDA is the exploratory data analysis; the data scientists mainly use the EDA to understand the main features of the data quickly, the variables in python and the relationship...

6 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.