الإنشاء المختصر للقوائم والقواميس
يُنشئ الإنشاء المختصر للقائمة (list comprehension) قائمة جديدة في سطر واحد: [n * n for n in numbers]، وهو أقصر من حلقة for مع .append().
يمكن إضافة شرط تصفية باستخدام if: تحتفظ [n for n in numbers if n % 2 == 0] بالأعداد الزوجية فقط. والفكرة نفسها موجودة للقواميس: {word: len(word) for word in words}.
numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
print(squares)
evens = [n for n in numbers if n % 2 == 0]
print(evens)
lengths = {word: len(word) for word in ["hi", "python"]}
print(lengths)