Beginner Codes/Python/List Comprehensions
47%

Instructions

Syntax

new_list = [expression for item in iterable]

List Comprehensions 🪄

Python-oda oru "superpower" dhaan List Comprehension! Oru list-a create panna namba normal-a 3-4 lines of code ezhudhanum. Aana List Comprehension use panna, orey line-la mudichidalam!

Normal For Loop vs List Comprehension

Oru list-la irukka numbers-a 2 aala multiply panni pudhu list-la podanum nu vechuppom.

The Old Way (4 lines) 🐢

nums = [1, 2, 3, 4, 5]
doubled = []
for x in nums:
    doubled.append(x * 2)
print(doubled) # Output: [2, 4, 6, 8, 10]

The Pro Way (1 line) 🚀

nums = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in nums]
print(doubled) # Output: [2, 4, 6, 8, 10]

Side-by-Side Execution ⚡

Kizhe ulla diagram-la rendu approach-um eppadi orey velaya seiyudhu nu paarunga!

List Comprehension vs For Loop

Side-by-Side Code
# Old Way (4 lines)
nums = [1, 2, 3, 4, 5]
doubled_old = []
for x in nums:
doubled_old.append(x * 2)
# List Comprehension Way (1 line)
doubled_new = [
x * 2 for x in nums
]
Click 'Run Code' to see both approaches run at the same time.
nums
1
2
3
4
5
* 2
doubled_new

Your Turn! (Unga neram!)

  1. [10, 20, 30] nu oru list-a prices variable-la create pannunga.
  2. List comprehension use panni, ovvoru price koodayum 5-a add panni new_prices la save pannunga.
  3. new_prices ah print pannunga!

Help

List ComprehensionsExercise 37/7740 XP
❴❵ script.py
python.code
python
Loading...
Terminal
Terminal — python
Beginner Codes Terminal v1.0.0
─────────────────────────────────────
Ready. Click "Run Code" to execute...
Ready
Piston APIPYTHON0 lines