Menu

List Comprehensions for Data Transformation

List Comprehensions for Data Transformation

List comprehensions provide a concise way to create lists by transforming or filtering existing collections.

Transforming Values

Suppose a business needs to calculate prices after applying a 10% discount.

prices = [1000, 1500, 2000, 2500]

discounted_prices = [

price * 0.90 for price in prices

]

print(discounted_prices)

The expression applies the same calculation to every element and creates a new list.

Filtering Values

You can include a condition to select only the elements that meet a requirement.

sales = [12000, 8000, 25000, 15000, 6000]

high_sales = [

value for value in sales if value >= 15000

]

print(high_sales)

This produces a list containing only sales values greater than or equal to 15,000.

Transforming and Filtering Together

temperatures = [18, 25, 32, 15, 28, 35]

high_temperatures_f = [

(temperature * 9 / 5) + 32

for temperature in temperatures

if temperature >= 25

]

print(high_temperatures_f)

This example filters temperatures before converting them from Celsius to Fahrenheit.

List comprehensions work well for straightforward transformations. For complex processing, regular loops or dedicated data manipulation libraries may be easier to read and maintain.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details