Apa itu List Comprehension?
List comprehension adalah cara singkat untuk membuat list baru berdasarkan list yang sudah ada atau iterable lainnya.
Sintaks Dasar
Sintaks dasar list comprehension adalah:
new_list = [expression for item in iterable if condition]
Contoh Penggunaan
Berikut beberapa contoh penggunaan list comprehension:
1. Membuat list kuadrat
squares = [x**2 for x in range(10)]
2. Filter angka genap
evens = [x for x in range(20) if x % 2 == 0]
Performa
List comprehension umumnya lebih cepat daripada loop for tradisional karena dioptimasi di level interpreter.
Contoh Kode
Berbagai contoh list comprehension
Python
# Contoh List Comprehension
# 1. Basic - kuadrat dari 0-9
squares = [x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 2. Dengan kondisi - hanya angka genap
evens = [x for x in range(20) if x % 2 == 0]
# Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 3. Nested - flattening list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6]
# 4. Dictionary comprehension
word_lengths = {word: len(word) for word in ['hello', 'world', 'python']}
# Output: {'hello': 5, 'world': 5, 'python': 6}