📉
Tutorials
  • Computer History
  • Function
    • Finance
      • Calculate
    • Manage Data
    • Date&Time
    • Strings and Character
  • Snippets
    • Web Application
      • Hugo
      • JavaScript
        • Stopwatch using JavaScript?
    • Note
    • Start Project
      • GitHub
      • GitLab
    • Python Programming
      • Strings and Character Data
      • List
      • Dictionaries
    • Data Science
      • Setting Option
      • Get Data
  • Link Center
    • Next Articles
    • Google
    • Excel VBA
    • Python
      • Notebook
    • WebApp
      • Vue.js
    • Finance
    • Project
      • Kids
        • Scratch
      • Finance
        • Plotly.js
        • Portfolio
      • Mini Lab
        • Systems Administration
        • Auto Adjust Image
      • Sending Emails
      • ECS
        • Knowledge Base
        • ระบบผู้เชี่ยวชาญ (Expert System)
        • Check product
        • Compare two SQL databases
      • e-Library
        • Knowledge base
        • การจัดหมวดหมู่ห้องสมุด
        • Temp
      • AppSheet
        • บัญชีรายรับรายจ่าย
      • Weather App
      • COVID-19
  • Tutorials
    • Data Science
      • Data Science IPython notebooks
    • UX & UI
      • 7 กฎการออกแบบ UI
    • Web Scraping
      • Scrape Wikipedia Articles
      • Quick Start
    • GUI
      • pysimple
        • Create a GUI
      • Tkinter
        • Python Tkinter Tutorial
      • PyQt
        • PyQt Tutorial
    • MachineLearning
      • การพัฒนา Chat Bot
      • AI ผู้ช่วยใหม่ในการทำ Customer Segmentation
      • Customer Segmentation
      • ตัดคำภาษาไทย ด้วย PyThaiNLP API
    • Excel & VBA
      • INDEX กับ MATCH
      • รวมสูตร Excel ปี 2020
      • How to Write Code in a Spreadsheet
    • Visualization
      • Bokeh
        • Part I: Getting Started
        • Data visualization
        • Plotting a Line Graph
        • Panel Document
        • Interactive Data Visualization
    • VueJS
      • VueJS - Quick Guide
    • Django
      • Customize the Django Admin
      • พัฒนาเว็บด้วย Django
    • Git
      • วิธีสร้าง SSH Key
      • Git คืออะไร
      • เริ่มต้นใช้งาน Git
      • การใช้งาน Git และ Github
      • รวม 10 คำสั่ง Git
      • GIT Push and Pull
    • Finance
      • Stock Analysis using Pandas (Series)
      • Building Investment AI for fintech
      • Resampling Time Series
      • Python for Finance (Series)
      • Stock Data Analysis (Second Edition)
      • Get Stock Data Using Python
      • Stock Price Trend Analysis
      • Calculate Stock Returns
      • Quantitative Trading
      • Backtrader for Backtesting
      • Binance Python API
      • Pine Script (TradingView)
      • Stocks Analysis with Pandas and Scikit-Learn
      • Yahoo Finance API
      • Sentiment Analysis
      • yfinance Library
      • Stock Data Analysis
      • YAHOO_FIN
      • Algorithmic Trading
    • JavaScript
      • Split a number
      • Callback Function
      • The Best JavaScript Examples
      • File and FileReader
      • JavaScript Tutorial
      • Build Reusable HTML Components
      • Developing JavaScript components
      • JavaScript - Quick Guide
      • JavaScript Style Guide()
      • Beginner's Handbook
      • Date Now
    • Frontend
      • HTML
        • File Path
      • Static Site Generators.
        • Creating a New Theme
    • Flask
      • Flask - Quick Guide
      • Flask Dashboards
        • Black Dashboard
        • Light Blue
        • Flask Dashboard Argon
      • Create Flask App
        • Creating First Application
        • Rendering Pages Using Jinja
      • Jinja Templates
        • Primer on Jinja Templating
        • Jinja Template Document
      • Learning Flask
        • Ep.1 Your first Flask app
        • Ep.2 Flask application structure
        • Ep.3 Serving HTML files
        • Ep.4 Serving static files
        • Ep.5 Jinja template inheritance
        • Ep.6 Jinja template design
        • Ep.7 Working with forms in Flask
        • Ep.8 Generating dynamic URLs in Flask
        • Ep.9 Working with JSON data
        • Ep.23 Deploying Flask to a VM
        • Ep.24 Flask and Docker
        • Ep. 25: uWSGI Introduction
        • Ep. 26 Flask before and after request
        • Ep. 27 uWSGI Decorators
        • Ep. 28 uWSGI Decorators
        • Ep. 29 Flask MethodView
        • Ep. 30 Application factory pattern
      • The Flask Mega-Tutorial
        • Chapter 2: Templates
      • Building Flask Apps
      • Practical Flask tutorial series
      • Compiling SCSS to CSS
      • Flask application structure
    • Database
      • READING FROM DATABASES
      • SQLite
        • Data Management
        • Fast subsets of large datasets
      • Pickle Module
        • How to Persist Objects
      • Python SQL Libraries
        • Create Python apps using SQL Server
    • Python
      • Python vs JavaScript
      • Python Pillow – Adjust Image
      • Python Library for Google Search
      • Python 3 - Quick Guide
      • Regular Expressions
        • Python Regular Expressions
        • Regular Expression (RegEx)
        • Validate ZIP Codes
        • Regular Expression Tutorial
      • Python Turtle
      • Python Beginner's Handbook
      • From Beginner to Pro
      • Standard Library
      • Datetime Tutorial
        • Manipulate Times, Dates, and Time Spans
      • Work With a PDF
      • geeksforgeeks.org
        • Python Tutorial
      • Class
      • Modules
        • Modules List
        • pickle Module
      • Working With Files
        • Open, Read, Append, and Other File Handling
        • File Manipulation
        • Reading & Writing to text files
      • Virtual Environments
        • Virtual Environments made easy
        • Virtual Environmen
        • A Primer
        • for Beginners
      • Functions
        • Function Guide
        • Inner Functions
      • Learning Python
        • Pt. 4 Python Strings
        • Pt. 3 Python Variables
      • Zip Function
      • Iterators
      • Try and Except
        • Exceptions: Introduction
        • Exceptions Handling
        • try and excep
        • Errors and Exceptions
        • Errors & Exceptions
      • Control Flow
      • Lambda Functions
        • Lambda Expression คืออะไร
        • map() Function
      • Date and Time
        • Python datetime()
        • Get Current Date and Time
        • datetime in Python
      • Awesome Python
      • Dictionary
        • Dictionary Comprehension
        • ALL ABOUT DICTIONARIES
        • DefaultDict Type for Handling Missing Keys
        • The Definitive Guide
        • Why Functions Modify Lists and Dictionaries
      • Python Structures
      • Variable & Data Types
      • List
        • Lists Explained
        • List Comprehensions
          • Python List Comprehension
          • List Comprehensions in 5-minutes
          • List Comprehension
        • Python List
      • String
        • Strings and Character Data
        • Splitting, Concatenating, and Joining Strings
      • String Formatting
        • Improved String Formatting Syntax
        • String Formatting Best Practices
        • Remove Space
        • Add Spaces
      • Important basic syntax
      • List all the packages
      • comment
    • Pandas
      • Tutorial (GeeksforGeeks)
      • 10 minutes to pandas
      • Options and settings
      • เริ่มต้น Set Up Kaggle.com
      • Pandas - Quick Guide
      • Cookbook
      • NumPy
        • NumPy Package for Scientific
      • IO tools (text, CSV, …)
      • pandas.concat
      • Excel & Google Sheets
        • A Guide to Excel
        • Quickstart to the Google Sheets
        • Python Excel Tutorial: The Definitive Guide
      • Working With Text Data
        • Quickstart
      • API Reference
      • Groupby
      • DateTime Methods
      • DataFrame
      • sort_values()
      • Pundit: Accessing Data in DataFrames
      • datatable
        • DataFrame: to_json()
        • pydatatable
      • Read and Write Files
      • Data Analysis with Pandas
      • Pandas and Python: Top 10
      • 10 minutes to pandas
      • Getting Started with Pandas in Python
    • Markdown
      • Create Responsive HTML Emails
      • Using Markup Languages with Hugo
    • AngularJS
      • Learn AngularJS
    • CSS
      • The CSS Handbook
      • Box Shadow
      • Image Center
      • The CSS Handbook
      • The CSS Handbook
      • Loading Animation
      • CSS Grid Layout
      • Background Image Size
      • Flexbox
  • Series
    • จาวาสคริปต์เบื้องต้น
      • 1: รู้จักกับจาวาสคริปต์
  • Articles
    • Visualization
      • Dash
        • Introducing Dash
    • Finance
      • PyPortfolioOpt
      • Best Libraries for Finance
      • Detection of price support
      • Portfolio Optimization
      • Python Packages For Finance
    • Django
      • เริ่มต้น Django RestFramework
    • General
      • Heroku คืออะไร
      • How to Crack Passwords
    • Notebook
      • IPython Documentation
      • Importing Notebooks
      • Google Colab for Data Analytics
      • Creating Interactive Dashboards
      • The Definitive Guide
      • A gallery of interesting Jupyter Notebooks
      • Advanced Jupyter Notebooks
      • Converting HTML to Notebook
    • Pandas
      • Pandas_UI
      • Pandas Style API
      • Difference Between two Dataframes
      • 19 Essential Snippets in Pandas
      • Time Series Analysis
      • Selecting Columns in a DataFrame
      • Cleaning Up Currency Data
      • Combine Multiple Excel Worksheets
      • Stylin’ with Pandas
      • Pythonic Data Cleaning
      • Make Excel Faster
      • Reading Excel (xlsx) Files
      • How to use iloc and loc for Indexing
      • The Easiest Data Cleaning Method
    • Python
      • pip install package
      • Automating your daily tasks
      • Convert Speech to Text
      • Tutorial, Project Ideas, and Tips
      • Image Handling and Processing
        • Image Processing Part I
        • Image Processing Part II
        • Image tutorial
        • Image Processing with Numpy
        • Converts PIL Image to Numpy Array
      • Convert Dictionary To JSON
      • JSON Dump
      • Speech-to-Text Model
      • Convert Text to Speech
      • Tips & Tricks
        • Fundamentals for Data Science
        • Best Python Code Examples
        • Top 50 Tips & Tricks
        • 11 Beginner Tips
        • 10 Tips & Tricks
      • Password hashing
      • psutil
      • Lambda Expressions
    • Web Scraping
      • Web Scraping using Python
      • Build a Web Scraper
      • Web Scraping for beginner
      • Beautiful Soup
      • Scrape Websites
      • Python Web Scraping
        • Web Scraping Part 1
        • Web Scraping Part 2
        • Web Scraping Part 3
        • Web Scraping Part 4
      • Web Scraper
    • Frontend
      • Book Online with GitBook
      • Progressive Web App คืออะไร
      • self-host a Hugo web app
  • Examples
    • Django
      • Build a Portfolio App
      • SchoolManagement
    • Flask
      • Flask Stock Visualizer
      • Flask by Example
      • Building Flask Apps
      • Flask 101
    • OpenCV
      • Build a Celebrity Look-Alike
      • Face Detection-OpenCV
    • Python
      • Make Game FLASH CARD
      • Sending emails using Google
      • ตรวจหาภาพซ้ำด้วย Perceptual hashing
        • Sending Emails in Python
      • Deck of Cards
      • Extract Wikipedia Data
      • Convert Python File to EXE
      • Business Machine Learning
      • python-business-analytics
      • Simple Blackjack Game
      • Python Turtle Clock
      • Countdown
      • 3D Animation : Moon Phases
      • Defragmentation Algorithm
      • PDF File
        • จัดการข้อความ และรูป จากไฟล์ PDF ด้วย PDFBox
      • Reading and Generating QR codes
      • Generating Password
        • generate one-time password (OTP)
        • Random Password Generator
        • Generating Strong Password
      • PyQt: Building Calculator
      • List Files in a Directory
      • [Project] qID – โปรแกรมแต่งรูปง่ายๆ เพื่อการอัพลงเว็บ
      • Python and Google Docs to Build Books
      • Tools for Record Linking
      • Create Responsive HTML Email
      • psutil()
      • Transfer Learning for Deep Learning
      • ดึงข้อมูลคุณภาพอากาศประเทศไทย
        • Image Classification
    • Web Scraper
      • Scrape Wikipedia Articles
        • Untitled
      • How Scrape Websites with Python 3
    • Finance
      • Algorithmic Trading for Beginners
      • Parse TradingView Stock
      • Creating a stock price database with MariaDB and python
      • Source Code
        • stocks-list
      • Visualizing with D3
      • Real Time Stock in Excel using Python
      • Create Stock Quote Module
      • The Magic Formula Lost Its Sparkle?
      • Stock Market Analysis
      • Stock Portfolio Analyses Part 1
      • Stock Portfolio Analyses Part 2
      • Build A Dashboard In Python
      • Stock Market Predictions with LSTM
      • Trading example
      • Algorithmic Trading Strategies
      • DOWNLOAD FUNDAMENTALS DATA
      • Algorithmic Trading
      • numfin
      • Financial Machine Learning
      • Algorithm To Predict Stock Direction
      • Interactive Brokers API Code
      • The (Artificially) Intelligent Investor
      • Create Auto-Updating Excel of Stock Market
      • Stock Market Predictions
      • Automate Your Stock Portfolio
      • create an analytics dashboard
      • Bitcoin Price Notifications
      • Portfolio Management
    • WebApp
      • CSS
        • The Best CSS Examples
      • JavaScript
        • Memory Game
      • School Clock
      • Frontend Tutorials & Example
      • Side Menu Bar with sub-menu
      • Create Simple CPU Monitor App
      • Vue.js building a converter app
      • jQuery
        • The Best jQuery Examples
      • Image Slideshow
      • Handle Timezones
      • Text to Speech with Javascript
      • Building Blog for Your Portfolio
      • Responsive Website Layout
      • Maths Homework Generator
  • Books
    • Finance
      • Python for Finance (O'Reilly)
    • Website
      • Hugo
        • Go Bootcamp
        • Hugo in Action.
          • About this MEAP
          • Welcome
          • 1. The JAM stack with Hugo
          • 2. Live in 30 minutes
          • 3. Using Markup for content
          • 4. Content Management with Hugo
          • 5. Custom Pages and Customized Content
          • 6. Structuring web pages
          • A Appendix A.
          • B Appendix B.
          • C Appendix C.
    • Python
      • ภาษาไพธอนเบื้องต้น
      • Python Cheatsheet
        • Python Cheatsheet
      • Beginning Python
      • IPython Cookbook
      • The Quick Python Book
        • Case study
        • Part 1. Starting out
          • 1. About Python
          • 2. Getting started
          • 3. The Quick Python overview
        • Part 2. The essentials
          • 14. Exceptions
          • 13. Reading and writing files
          • 12. Using the filesystem
          • 11. Python programs
          • 10. Modules and scoping rules
          • 9. Functions
          • 8. Control flow
          • 4. The absolute basics
          • 5. Lists, tuples, and sets
          • 6. Strings
          • 7. Dictionaries
        • Part 3. Advanced language features
          • 19. Using Python libraries
          • 18. Packages
          • 17. Data types as objects
          • 16. Regular expressions
          • 15. Classes and OOP
        • Part 4. Working with data
          • Appendix B. Exercise answers
          • Appendix A. Python’s documentation
          • 24. Exploring data
          • 23. Saving data
          • 20. Basic file wrangling
          • 21. Processing data files
          • 22. Data over the network
      • The Hitchhiker’s Guide to Python
      • A Whirlwind Tour of Python
        • 9. Defining Functions
      • Automate the Boring Stuff
        • 4. Lists
        • 5. Dictionaries
        • 12. Web Scraping
        • 13. Excel
        • 14. Google Sheets
        • 15. PDF and Word
        • 16. CSV and JSON
    • IPython
    • Pandas
      • จัดการข้อมูลด้วย pandas เบื้องต้น
      • Pandas Tutorial
  • Link Center
    • Temp
  • เทควันโด
    • รวมเทคนิค
    • Help and Documentation
  • Image
    • Logistics
Powered by GitBook
On this page
  • What else can you do with Python list comprehensions?
  • Over 100 and odd
  • What’s next?
  • Python – List Comprehensions
  • What is a List Comprehension and What is its Purpose?
  • List Comprehension Syntax:
  • Example Scenario:
  • Generate Strings with List Comprehensions:
  • Nested List Comprehensions:

Was this helpful?

  1. Tutorials
  2. Python
  3. List
  4. List Comprehensions

List Comprehensions in 5-minutes

A visual introduction to those tricky Pythonic one-liners

PreviousPython List ComprehensionNextList Comprehension

Last updated 4 years ago

Was this helpful?

Just show me the code! Quick link:

Why would you want to do a Python list comprehension?

To save lines of code.

There’s might be more to it than that but in my experience, this is the only reason — if you have a better one, leave a comment and I’ll update the article.

You can get the exact same thing done with a couple extra lines. But browse any Python Stack Overflow question and chances are you’ll find someone asking for a Pythonic version or a Pythonic one-liner.

List comprehensions are a way of achieving Pythonic one-liners with iterables (lists).

One-line definitions:

  • List = a Python object which can be iterated over (an iterable).

  • Iterated over = going through something one-by-one.

A good example is emptying your shopping cart at the cashier, you pull each item out one by one and put it on the counter, your shopping cart could be considered an iterable.

We’ll use this example to look at some code. We’re shopping at a math store so all we’re buying is numbers.

# Create a list of numbers (our shopping cart)
cart = [3, 4, 12, 17, 19, 21, 23, 26, 30]# Pass items to the cashier
cashier = []
for item in cart:
    cashier.append(item)
print(cashier)# The output is the same as the cart
Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]

What happened here?

  1. We created a list of items in the cart

  2. We created an empty cashierlist (the cashierdidn’t have any of our items yet)

  3. We used a for loop to iterate over each itemin our cart

  4. For each itemwe added it to the cashier list with .append()

  5. Then we checked what items the cashier had with print()

How could we do this same thing a list comprehension?

# Pass items to second cashier but with a list comprehension
cashier_2 = [item for item in cart]
print(cashier_2)# The output is the same as cashier (and the same as cart)
Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]

What happened here?

The exact same steps as above, only written in a different way. Let’s compare.A non-list comprehension and list comprehension comparison of the same code.

  1. cashier is created in blue. On the left, it’s created on its own line. On the right, it’s created at the same time everything else is being created.

  2. cart is being iterated over in green. item is created as the for loop runs. This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier.

  3. cashier is updated in the red with each item. The only difference is on the left, an .append() statement is required. The list comprehension on the right negates the need for an .append() statement

We accomplished the same steps in 1 line of code instead of 3. This may not seem like much but say you had a 1000 line Python project. You could potentially reduce your project from 1000 lines to 300. This kind of reduction won’t always happen but it’s an example of how to get the same task done with a Pythonic one-liner.

What else can you do with Python list comprehensions?

Now you’ve got a little bit of an intuition, let’s look at a few more examples.

cashier_3 only deals with even numbers. How could we deal with this?

By using a conditional.

  • Conditional = another way of saying, do something if True, stop if False.

# Make a new cart
cart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Only give cashier_3 even numbers
cashier_3 = []
for item in cart:
    if item % 2 == 0:
        cashier_3.append(item)
print(cashier_3)# Thanks to the conditional the output is only the even numbers
Output: [10, 12, 20, 22]

How about with a list comprehension?

cashier_3 = [item for item in cart if item % 2 == 0]
print(cashier_3)# The output is the same as above
Output: [10, 12, 20, 22]

What’s happening here?Example of a non-list comprehension and a list comprehension with a conditional.

This is similar to the above example except for the conditional in yellow.

  1. cashier_3 is created in blue.

  2. cart is being iterated over in green. item is being created as the for loop runs.

  3. As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow.

  4. cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow.

Over 100 and odd

cashier_4 only accepts numbers over 100 and are odd. How could you do this?

# Reminder of what cart looks like
cart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Non-list comprehension for cashier_4
cashier_4 = []
for item in cart:
    item += 100 # add 100 to each item to bring them over 100
    if item % 2 == 1: # check to see if they're odd or not
        cashier_4.append(item)
print(cashier_4)# The output is all odd numbers over 100
Output: [105, 107, 109, 115, 119]

Now with a list comprehension.

# List comprehension for cashier_4
cashier_4 = [item+100 for item in cart if item % 2 == 1]
print(cashier_4)# The output is all odd numbers over 100 (same as above)
Output: [105, 107, 109, 115, 119]

What’s next?

This tutorial only scratches the surface of what’s possible with Python list comprehensions. Once you start to get the hang of them, you’ll start to realise how valuable they are for writing succinct and powerful Pythonic code.

Python – List Comprehensions

In Python you can use list comprehensions to shorten the amount of code that you need to use to accomplish tasks when working with lists. The first time I heard of list comprehensions it sounded very advanced and confusing and when I looked at some example code I was, as I expected confused. Fear not list comprehensions are just as simple as a for loop and once you understand them you will begin to use them in your code to solve problems in much more elegant ways and conserving unneeded lines of code.

What is a List Comprehension and What is its Purpose?

List Comprehension Syntax:

You can think of a list comprehension as a single line for loop enclosed in brackets (thats because it pretty much is) with the operation your performing coming first and the for loop statement coming second. Below I have a visual representation of a traditional for loop and where you place it in a list comprehension

As you can see the code in the blue square (the operation your performing) comes first inside the brackets and the code in the red square (for loop statement minus the colon “:”) comes second.

With this visual representation I hope it is easy to see that a list comprehension can be thought of as a reverse single line for loop.

Example Scenario:

Lets say we have a list of numbers and we need to add 5 to each of those numbers and print them out to the user. Below I have an example using a for loop to accomplish that task and then I solve the same problem using a list comprehension.

For Loop:

#!/usr/bin/python3
 
# List of numbers to be displayed to the user
list_of_numbers = [2, 5, 16, 20]
 
# Define new list
list_to_be_displayed = []
 
# For loop to add 5 to each of the numbers in my list
for number in list_of_numbers:
    list_to_be_displayed.append(number + 5)
 
# Prints the new numbers out to the user
for number in list_to_be_displayed:
    print(number)

Now I will be the first to admit there are more elegant ways to solve this without the need to use 2 for loops, for instance I could have added print(number + 5) inside the first for loop to remove the need for a second for loop but at the same time I would be doing the math twice vs a second for loop. Now lets solve the same problem using a list comprehension.

List Comprehension:

#!/usr/bin/python3
 
# List of numbers to be displayed to the user
list_of_numbers = [2, 5, 16, 20]
 
# Adds 5 to each number in the list of numbers
list_of_numbers = [number + 5 for number in list_of_numbers]
 
# prints out each number to the user
[print(number) for number in list_of_numbers]

Running both of the code snippets gives us the following output:

User@Laptop> forloop.py
7
10
21
25
User@Laptop>

The mechanics of what is happening in both examples is almost the exact same the only exception is we are not creating a new list for the new numbers, instead the list comprehension at line 7 allows us to overwrite our existing list variable with the new values. We have reduced our total overall code by 5 lines but we still use 2 list comprehensions to first do the addition to each of the numbers and the second to print them to the user because we have kept our for loops to a single line.

Generate Strings with List Comprehensions:

Another useful way to use list comprehensions is when generating strings using values in a list, below I have an example based on the original one above to create a human readable string of the added numbers to display to the user that reads “My following numbers are 7 and 10 and 21 and 25”

Using For Loop:

#!/usr/bin/python3

# List of numbers to be displayed to the user
list_of_numbers = [2, 5, 16, 20]

#creates string variable
string = ''

# takes our list, adds 5 to each number and appends that number with the word " and " to the string
for number in list_of_numbers:
    string += '{} and '.format(number + 5)
# Removes the last word " and " from our string
string = string[:-5]
# Prints out to the user
print('My following numbers are {}'.format(string))

When using a for loop we have to create a new variable for the string, then we have to use a for loop to generate the custom part of our string (## and ## and etc.) then we need to remove the final and from the custom part of our string before we can finally print it to the user

Using List Comprehension:

#!/usr/bin/python3

# List of numbers to be displayed to the user
list_of_numbers = [2, 5, 16, 20]

# prints out each number to the user
print('My following numbers are {}'.format(' and '.join([str(number + 5) for number in list_of_numbers])))

Using a list comprehension we have shaved 8 lines off of our code and done all of the work in a single line. Now I will be the first to admit to understand the mechanics of what is happening here you need to analyze line 7 alittle harder but once you start getting comfortable reading more complex list comprehensions that one line it is easy to see what is happening.

Here is the breakdown of what is happening in line 7:

First the list comprehension is generating a new list and that list will contain the product of each of the numbers and 5 storing it as a string in the list that is being generated. That code is the list comprehension itself.

[str(number + 5) for number in list_of_numbers]

Second that list of strings is put together in the following format “## and ## and ## and ##”. That is done by using the join() method which has the list comprehension nested inside of it. Note the join() method is smart enough not to add the word “and” after the last element in the list so we don’t need to handle it like we did before.

' and '.join([str(number + 5) for number in list_of_numbers])

At this point we have our custom string generated, formatted, and ready to be attached to the static part of our string.

'My following numbers are {}'.format(' and '.join([str(number + 5) for number in list_of_numbers]))

And finally it is printed out to the user by encasing all of that within a print statement.

print('My following numbers are {}'.format(' and '.join([str(number + 5) for number in list_of_numbers])))

Running both of the code snippets gives us the following output:

User@Laptop> test.py
My following numbers are 7 and 10 and 21 and 25
User@Laptop>

Nested List Comprehensions:

You can also nest list comprehensions much like you nest for loops so for instance if you have a list of lists and you need to run a list comprehension over each element in the nested lists this can be accomplished by using a list comprehension. Below I show you an example of adding 1 to each element in a list of lists, the first block I will show you using a for loop and the second i will show you using a list comprehension.

#!/usr/bin/python3
 
# generates list and prints it out
mylist = [[1, 2, 3], [4, 5, 6]]
print('Original List: {}'.format(mylist))
 
# adds 1 to each element of each list within the main list
for list in mylist:
    counter = 0
    for element in list:
        addition = element + 1  # adds 1 to the current element
        list.pop(counter)  # removes current element
        list.insert(counter, addition)  # inserts new number
        counter += 1  # increments counter
 
# prints list
print('Modified List: {}'.format(mylist))
#!/usr/bin/python3
 
# generates list and prints it out
mylist = [[1, 2, 3], [4, 5, 6]]
print('Original List: {}'.format(mylist))
 
# adds 1 to each element of each list within the main list and prints list
mylist = [[element + 1 for element in list] for list in mylist]
print('Modified List: {}'.format(mylist))

Running both of these code examples gives us the following result.

User@Laptop> test.py
Original List: [[1, 2, 3], [4, 5, 6]]
Modified List: [[2, 3, 4], [5, 6, 7]]
User@Laptop>

As you can see running each snippet of code they yield the same result but using a list comprehension takes off 8 lines of code that is the nested for loop and does everything in one line. Using the list comprehension we do not have to create any intermediate variables to count the number of loops or hold temporary data we simply re declare the same variable of our list “mylist” and set it equal to the list comprehension and it takes care of all of the heavy lifting for us which allows us to have cleaner and more understandable code.

If understanding what is happening when translating a nested for loop into a list comprehension is hard for you to see below I have another visual representation as to where each part of the for loop goes into a list comprehension.

Looking at the picture we can see that in the list comprehension we have 2 sets of square brackets with the outer most of the for loop (red) in the outer most bracket, and the inner for loop (blue) inside the inner brackets with the operation we are performing (green) prepended to the beginning inside the inner brackets.

I hope that this article has cleared up any mystery with list comprehensions and I was able to provide some useful examples. If you have any questions please drop a comment below and I will be sure to get back to you with an answer as soon as possible and if this article was helpful please share on social media!

Image for post
Image for post

If you’re looking for more, I recommend checking out the .

All the code in this article is and a video version of this article is .

Reference :

A list comprehension is a concept in Python that’s used to generate a list. Its purpose is to allow a programmer to generate a list in a more fluent and efficient way and use less code in the process than if you were to use a for loop to generate a list. If you do not understand what a List is in python check out my post to become more familiar with lists.

Third our custom string is joined with the static part of our string by using the format() method with this code. (If you would like to understand more on string formatting check out my )

Reference :

Python list comprehension tutorial on DataCamp
available on GitHub
available on YouTube
https://towardsdatascience.com/python-list-comprehensions-in-5-minutes-40a68cbe4561
linked here
post linked here
https://kyletk.com/index.php/2018/03/24/python-list-comprehensions/
Feb 9, 2019
Jupyter Notebook on GitHub