Home Backend Development Python Tutorial An elegant and simple way to use Python Lists: List Comprehensions

An elegant and simple way to use Python Lists: List Comprehensions

Sep 28, 2024 am 08:10 AM

An elegant and simple way to use Python Lists: List Comprehensions

You might think List Comprehension is an advanced concept. However, it can simplify your code with just one line in tricky situations. It's time to understand how it works. I will explain it at a beginner level with examples.

What Exactly is List Comprehension?

You often see the notation l2 = [x 1 for x in l]. It's said to be the same as this:

l2 = []
for x in l:
    x = x + 1
l2.append(x)
Copy after login

For both cases, if we start with l = [10, 100, 1000], l2 will be:

[11, 101, 1001]
Copy after login

The first syntax is what we call list comprehension.
You may prefer the usual for loop, but by the end of this article, I promise you’ll be confident using list comprehension!

In addition, let's check the detailed official definition from the documentation https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Let's break it down more. List comprehension is just a different way to write code that is shorter and easier to make a new list. The result of list comprehension is a list, which is why we assign it to a list.
Let's go over the second part of the definition, which discusses common examples. This should be done using specific examples.
1.

fast_foods = ["Burger", "Pizza", "Tacos", "Fried Chicken", "Hot Dog"]
uppercase_fast_foods = [food.upper() for food in fast_foods]
Copy after login

After this, uppercase_fast_foods will be:

['BURGER', 'PIZZA', 'TACOS', 'FRIED CHICKEN', 'HOT DOG']
Copy after login

We use the upper() function to change each food item in our list to uppercase. As a result, all items are now in uppercase. This is how we 'make new lists where each element is the result of some operations applied to each member of another sequence or iterable.'
2.

fast_foods = ["Burger", "Pizza", "Tacos", "Fried Chicken", "Hot Dog"]
foods_with_space = [food for food in fast_foods if " " in food]
Copy after login

After this, foods_with_space will be:

['Fried Chicken', 'Hot Dog']
Copy after login

The line of code above retrieves the items from the list that contain a whitespace character. This is how we 'make new lists where each element is the result of some operations applied to each member of another sequence or iterable.'

Examples of List Comprehension

I’ve used list comprehensions in many problems because whenever I encountered too many for-loops, I thought, 'No problem, I’ll just simplify them.' Turns out, it’s the same logic, just cleaner! ?
Without further ado, here are some of the most relevant examples I’ve come up with:
1. Modify each element of the list

foods = ["Burger", "Fries", "Fried Chicken", "Hot Dog", "Pizza"]
foods_with_version = [food + ' - 2024' for food in foods]
print(foods_with_version)
Copy after login

Output:

['Burger - 2024', 'Fries - 2024', 'Fried Chicken - 2024', 'Hot Dog - 2024', 'Pizza - 2024']
Copy after login

In this example, we take a list of food items and add '- 2024' to each one. We use list comprehension to quickly create a new list with these updated names.
2. Make a sublist from a list based on a condition

foods = ["Burger", "Fried Chicken", "Hot Dog", "Fries", "Pizza"]
long_foods = [food for food in foods if len(food) > 7]
print(long_foods)
Copy after login

Output:

['Fried Chicken']`
Copy after login

In this example, we create a list of food items and filter out the ones that have more than 7 characters. We use list comprehension with a condition to achieve this.
3. Use the range function with list comprehension to create a list

x = [i for i in range(10, 20, 2)]
print(x)
Copy after login

Output:

[10, 12, 14, 16, 18]
Copy after login

In this example, we create a list of numbers ranging from 10 to 18 using list comprehension with range().
4. Apply list comprehension to a string

input_string = "hello world"
marked_vowels = ['*' if char in 'aeiouAEIOU' else char for char in input_string]
print(marked_vowels)
Copy after login

Output:

['h', '*', 'l', 'l', '*', ' ', 'w', 'o', 'r', 'l', 'd']
Copy after login

In this last example, we take a string and mark its vowels with an asterisk (*). We use list comprehension to create a new list based on the original string.

Conclusion

Throughout this article, I’ve covered all the basic insights about list comprehensions, from the definition to various examples that explain them further. I hope everything is clear, and you feel more motivated to incorporate list comprehensions into your Python code from now on!

The above is the detailed content of An elegant and simple way to use Python Lists: List Comprehensions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles