Python List Comprehension

In today’s lesson, we will discuss Python lists comprehension with examples in order to achieve the learning objectives.

Python Lists comprehension Advantages

  1. Compared to loops, it is more space and time efficient.
  2. Streamline the coding process.
  3. Formulates iterative statements.


Py Lists Comprehension

When it comes to Python lists comprehension, list comprehension offers a simpler syntax for creating a new list based on existing values.

Example:

The goal is to create a new list containing only countries whose names start with the letter “U”.

If you do not have list comprehension, you will have to write a for statement with a conditional test in it:

Example: 

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] country_newlist = [] for i in country_list: if "U" in i: country_newlist.append(i) print(country_newlist)

Python lists comprehension makes all that possible with just one line of code:

Example: 

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] country_newlist = [i for i in country_list if "U" in i] print(country_newlist)

Python Lists comprehension examples


Syntax

newlist = [In an iterable if condition, the expression for the item == True]

When it comes to Python lists comprehension, the return value is a new list, leaving the old list unchanged.


Iterable

You can iterate over any iterable object, such as a list, tuple, set, etc.

Example:  The range() function creates an iterable as follows:

current_list = [i for i in range(10)] print(current_list)

This example is the same as the previous one, but with a condition:

Example:  Numbers less than 7 should be accepted:

current_list = [i for i in range(10) if i < 8] print(current_list)

Condition

This condition is similar to a filter, which accepts only true items.

Accept only items that are not “Denmark”:

Example: 

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] country_newlist = [i for i in country_list if i != "Denmark"] print(country_newlist) #you can do the above task by applying "!=" operator country_newlist = [i for i in country_list if "Denmark" not in i] print(country_newlist) #you can also do the above task by applying "not" and "in" keyword.

The situation if i != “Denmark” Returns True for all elements except

As a result, the new list contains all countries except “Denmark”.

The requirement is non-essential and can be excluded:

Example:  In the absence of an if statement:

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] country_newlist = [i for i in country_list] print(country_newlist)

What You Need to Know ?

  1. Based on existing lists, Python lists comprehension defines and creates new lists.
  2. The process of creating a list using list comprehension is usually more compact and faster than using functions and loops to create the list.
  3. If we want to keep our code user-friendly, we should avoid writing very long lists of comprehensions on one line.
  4. The for loop cannot be rewritten in the form of a list comprehension, but every list comprehension can be rewritten in the form of a for loop.
  5. Like nested for loops, nested list comprehensions are just list comprehensions nested within each other.

Expression

In Python lists comprehension, the expression is the current item in the iteration, but it is also the outcome, which can be modified before it becomes a list item in the newlist:

In the new list, make sure that all the values are in upper case:

Example: 

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] current_list = [i.upper() for i in country_list] print(current_list)

The outcome can be set to whatever you want:

Example:  Make all values in the updated list ‘greetings’:

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] current_list = ["greetings" for i in country_list] print(current_list)

A condition can also be added to the expression, not as a filter, but as a way to manipulate the result:

Example:  Rather than “Maldives”, return “Ireland”:

country_list = [ "United States of America", "United Kingdom", "Finland", "Brazil", "Germany", "Spain", "Maldives", "Croatia", "Denmark", "Italy"] current_list = [i if i != "Maldives" else "Ireland" for i in country_list] print(current_list)

The statement in the illustration above indicates:

“The item must be returned if it is not Maldives, if it is Maldives it must be returned to Ireland”


Python List Comprehension Importance

Here are some reasons why list comprehension is important in Python:

  1. List comprehensions provide a compact syntax for creating lists in a single line of code. This leads to more concise and readable code, especially when compared to writing traditional for loops or using lambda functions. List comprehensions allow you to express your intentions directly, making the code more understandable and maintainable.
  2. List comprehensions are optimized by the Python interpreter and often offer better performance than equivalent for loops. They can be faster and more efficient because they utilize highly optimized C-based operations behind the scenes. This makes list comprehensions an excellent choice when you need to process large datasets or perform complex transformations on lists.
  3.  List comprehensions enable you to transform each element of an existing list and create a new list based on the transformed values. This is particularly useful when you need to apply a consistent operation or function to each item in the list. List comprehensions allow you to express the transformation succinctly, enhancing code readability.
  4. List comprehensions also provide a convenient way to filter elements from an existing list based on specific conditions. You can include an if statement within the list comprehension to selectively include or exclude elements from the resulting list. This makes it easy to create a new list that contains only the desired elements that meet specific criteria.
  5. List comprehensions embrace the principles of declarative programming by focusing on “what” needs to be achieved rather than “how” it should be done. They allow you to express your intent clearly and concisely. With list comprehensions, you can write code that closely resembles the mathematical notation, improving code expressiveness.
Get the inside scoop on upcoming events and promotions by subscribing to our Newsletter.

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *