Lesson 27 of 34

List Comprehensions: ஒரே வரியில் listList Comprehensions: Lists in One Line

8 min 30 XP

ஒரு list-ஐ loop மூலம் உருவாக்குவதை ஒரே வரியில் எழுதலாம்: [வெளிப்பாடு for உருப்படி in தொகுப்பு]. இது Python-ன் மிகவும் பிரபலமான அம்சம்.

Building a list with a loop can be written in one line: [expression for item in collection]. It's one of Python's most loved features.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

கடைசியில் if சேர்த்தால், நிபந்தனை உண்மையானவை மட்டும் சேரும் (filter).

Add an if at the end to keep only the items that match (a filter).

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

{ } பயன்படுத்தினால் dictionary comprehension. மிக நீளமான comprehension-ஐ சாதாரண loop ஆக எழுதுவதே படிக்க எளிது.

Use { } for a dictionary comprehension. If a comprehension gets very long, a normal loop is easier to read.

Challenge

+30 XP

list comprehension பயன்படுத்தி 1 முதல் 10 வரை உள்ள இரட்டைப்படை எண்களின் வர்க்கங்களை (squares) ஒரு list-ஆக print செய்யுங்கள்: [4, 16, 36, 64, 100]

Use a list comprehension to print the squares of the even numbers from 1 to 10 as a list: [4, 16, 36, 64, 100]

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.