Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

List Comprehensions

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

List Comprehensions များသည် lists များကို concise way ဖြင့် create လုပ်နိုင်စေသည်။ Dictionary နှင့် Set comprehensions များလည်း ရှိသည်။

📝 Syntax:

• List: [expression for item in iterable if condition]

• Dict: {key: value for item in iterable}

• Set: {expression for item in iterable}

python
# List comprehension
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")

# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(f"Evens: {evens}")

# Nested comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(f"Matrix: {matrix}")

# Dictionary comprehension
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Dict: {square_dict}")

# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(f"Lengths: {unique_lengths}")
You should see
Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Evens: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Matrix: [[1, 2, 3], [2, 4, 6], [3, 6, 9]] Dict: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Lengths: {5, 6}