List Comprehension In Python

Locked-in Secrets About List Comprehension #PurePythonSeries — Episode #06

J3
Jungletronics
5 min readOct 18, 2021

--

Covered topics:

How to Use List Comprehension;
The Difference between FOR and List Comprehension;
Using tuples to ensure maintenance of the order of dependent lists;
Applying List Comprehension In Classification Using Tuples;
How to Filtering Using IF CONDITION inside a List Comprehension;
IF ELSE of List Comprehension;
Does list comprehension always create a list in Python?

1 — Suppose you want to update taxes for a product list.

You have two lists, one for prices and another for products.

Your manager wants you to update 2019’s list prices by calculating the tax to be added (30 percent tax increase):

prd_prices_2019 = [100,150,300,5500]prds = ['Wine', 'Coffe Machine', 'Microwave', 'Iphone']

Usual way:

Using for loop (three lines)

taxes = []for price in prd_prices_2019:    taxes.append(price * 0.3)

The result:

print(taxes)[30.0, 45.0, 90.0, 1650.0]

One-Line Way:

Using List Comprehension (just one line)

LIST COMPREHENSION = [Expression for item in iterable]

taxes = [price * 0.3 for price in prd_prices_2019]

The result:

taxes[30.0, 45.0, 90.0, 1650.0]

Reporting professionally :)

Well, not quite actually lol:

total_before_tax = 0total_plus_tax = 0for price in prd_prices_2019:    total_before_tax += price    total_plus_tax +=  price * 1.3

The result:

print(f'Before taxation the stock of products was worth ${total_before_tax:.2f};\nAfter taxation the stock increased to ${total_plus_tax:.2f};\nThe inflationary difference is ${total_plus_tax - total_before_tax:.2f},\nwhich corresponds inflation of {((total_plus_tax - total_before_tax)/total_before_tax)*100:.2f} %')Before taxation the stock of products was worth $6050.00;
After taxation the stock increased to $7865.00;
The inflationary difference is $1815.00,
which corresponds inflation of 30.00 %

2 — Applying List Comprehension In Classification Using Tuples:

You cannot sort lists independently, because you can shuffle them, and lose sales order:/

First, you need to transform them into tuples (which are immutable).

Then, use List Comprehension to tell which product sells the most by sorting them out by values. See below:

Look:

prd_value_sales_2019 = [1500, 150, 2100, 1950]prds = ['Wine', 'Coffee Machine', 'Microwave', 'Iphone']

List of Tuples

prds_n_sales_2019 = list(zip(prd_value_sales_2019, prds))

The result:

prds_n_sales_2019[(1500, 'Wine'),
(150, 'Coffee Machine'),
(2100, 'Microwave'),
(1950, 'Iphone')]

OK, now that you’ve frozen the ranking of each product’s list, sort it out now, and finally use List Comprehension.

Please, realize that the value comes first so that the method can sort it out by value.

Now done in the reverse sortition:

Sorting in the reverse order:

prds_n_sales_2019.sort(reverse = True)prds_n_sales_2019[(2100, 'Microwave'),
(1950, 'Iphone'),
(1500, 'Wine'),
(150, 'Coffee Machine')]

Using List Comprehension:

top_selling_prds_2019 = [prd for value, prd in prds_n_sales_2019]

The result:

print(f'Here are the top selling products: {top_selling_prds_2019}')Here are the top selling products: ['Microwave', 'Iphone', 'Wine', 'Coffee Machine']

3 — Returning a Tuple:

We now have two consecutive years of sales (2019 and 2020) of each product inside a tuple.

Solve with List Comprehension which is the top-selling for 2020:

prd_value_sales_2019_2020  = [('Wine', 100, 1750), ('Coffee Machine', 150, 780), ('Microwave', 300, 178), ('Iphone', 5500, 500)]

Usual way:

Unpacking only the necessary information.

Using for loop (three lines):

value_sales_2020 = []for prd,sales_2019, sales_2020 in prd_value_sales_2019_2020:    value_sales_2020.append(sales_2020)

The result:

print(value_sales_2020)[1750, 780, 178, 500]

One-Line Way:

Using List Comprehension (just one line)

LIST COMPREHENSION = [Expression for item in iterable]

value_sales_2020 = [sales_2020 for pdr, sales_2019, sales_2020 in prd_value_sales_2019_2020 ]

The result:

value_sales_2020[1750, 780, 178, 500]

Or returning tuples:

prd_value_sales_2020 = [(sales_2020, prd) for prd, sales_2019, sales_2020 in prd_value_sales_2019_2020]

The result:

prd_value_sales_2020[(1750, 'Wine'), (780, 'Coffee Machine'), (178, 'Microwave'), (500, 'Iphone')]

Classifying:

prd_value_sales_2020.sort(reverse=True)prd_value_sales_2020[(1750, 'Wine'), (780, 'Coffee Machine'), (500, 'Iphone'), (178, 'Microwave')]

4 — Filtering Using IF CONDITION:

Now return only the products that hit the company’s sales target

Using List Comprehension (just one line)

LIST COMPREHENSION = [Expression for item in iterable IF CONDITION]

sales_target = 1500

Unpacking:

sales_2019_EXCEED_THE_GOAL = [(pdr,sales_2019) for pdr, sales_2019, sales_2020 in prd_value_sales_2019_2020 if sales_2019 > sales_target]

The result for 2019:

sales_2019_EXCEED_THE_GOAL[('Iphone', 5500)]

For 2020:

sales_2020_EXCEED_THE_GOAL = [(pdr,sales_2020) for pdr, sales_2019, sales_2020 in prd_value_sales_2019_2020 if sales_2020 > sales_target]

The result:

sales_2020_EXCEED_THE_GOAL[('Wine', 1750)]

5 — IF ELSE of List Comprehension

The general syntax of list comprehension in Python with if … else is:

[f(x) if condition else g(x) for x in list]

The bonus (10%)
goes for those who exceed sales goals:

sales_goal = 1500

Coworker work:)

coworker_sales_2020  = {'John':1897, 'Newton':1175, 'Maria':1501, 'Stephany':1601}

By the usual way:

extra = []for order in coworker_sales_2020:    if coworker_sales_2020[order] > sales_goal:        extra.append(round(coworker_sales_2020[order] * 0.1))    else:        extra.append(0)

The result:

print(extra)[190, 0, 150, 160]

By List Comprehension:

extra = [round(coworker_sales_2020[order] * 0.1) if coworker_sales_2020[order] > sales_goal else 0 for order in coworker_sales_2020]

The same result:

print(extra)[190, 0, 150, 160]

6 — Does list comprehension always create a list in Python?

NO! What you probably want is a generator expression!

Let us suppose you want to get the coworker who sold over 1500 and add the total — Total_Top_3_Vendor!

Let’s first remember dictionaries!

d = {'x': 1, 'y': 2, 'z': 3}for key in d:     print(key, 'corresponds to', d[key])x corresponds to 1
y corresponds to 2
z corresponds to 3

Now Let’s get it on:

coworker = []sales = []for key in coworker_sales_2020:     coworker.append(key)     sales.append(coworker_sales_2020[key])print(coworker)print(sales)['John', 'Newton', 'Maria', 'Stephany']
[1897, 1175, 1501, 1601]

Aggregation Functions (SUM) using List Comprehension:

Total_Top_3_Vendor = sum(sales[i] for i, vendor in enumerate(coworker) if sales[i] > sales_goal)

The result:

print(Total_Top_3_Vendor)4999

That’s all folks o/

print("That's it! I Hope you enjoyed this post! Subscribe to the Channel. Bye!")That's it! I Hope you enjoyed this post! Subscribe to the Channel. Bye!

Until next time!

👉Jupiter notebook link :)

👉or collab link

👉Github (PPY-06)

Credits & References

Hashtag Treinamentos by João Paulo Rodrigues de Lira — Thank you dude!

Related Posts

00#Episode#PurePythonSeries — Lambda in Python — Python Lambda Desmistification

01#Episode#PurePythonSeries — Send Email in Python — Using Jupyter Notebook — How To Send Gmail In Python

02#Episode#PurePythonSeries — Automate Your Email With Python & Outlook — How To Create An Email Trigger System in Python

03#Episode#PurePythonSeries — Manipulating Files With Python — Manage Your Lovely Photos With Python!

04#Episode#PurePythonSeries — Pandas DataFrame Advanced — A Complete Notebook Review

05#Episode#PurePythonSeries — Is This Leap Year? Python Calendar — How To Calculate If The Year Is Leap Year and How Many Days Are In The Month

06#Episode#PurePythonSeries — List Comprehension In Python — Locked-in Secrets About List Comprehension (this one)

07#Episode#PurePythonSeries — Graphs — In Python — Extremely Simple Algorithms in Python

08#Episode#PurePythonSeries — Decorator in Python — How To Simplifying Your Code And Boost Your Function

Image from this link

Note About List Comprehension by Dr. Angela Yu:

The big topic that we're going to explore today is a concept known as a list comprehension. And as I mentioned before,this is something that's really unique to the Python language.In many other programming languages,you don't actually have access to something like this.There's nothing that really compares to it.And it's something that Python developers really,really love because it cuts down on the amount of typing and it just makes the code a lot shorter, and in most cases, a lot easier to read.
[ Angela Yu in 100 Days of Code: The Complete Python Pro Bootcamp for 2022 (Episode #234. How to Create Lists using List Comprehension) ]

Code example:

new_list = [new_item for item in list]
new_list = [new_item
for item in list if test]
^ ^ ^ ^ ^
new_names name.upper() name names len(name)>5
names = ["Jaythree", "Jungletronics", "Kidstronics"]new_names = [name.upper() for name in names if len(names)>5]
print(new_names)
["JAYTHREE", "JUNGLETRONICS", "KIDSTRONICS" ]

>review in Nov, 2022 (fix code and add Yu note above)

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!