📅 2012-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ comprehension, list, python ⬩ 📚 Archive
A list comprehension is a convenient method to create lists in Python.
= [ i for i in range( 5 ) ]
a # [0, 1, 2, 3, 4]
= [ i for i in range( 5 ) if 0 == ( i % 2 ) ]
a # [0, 2, 4]
# In general any sequence of for and if
= [ i for ... if ... for ... for ... if ... ] a
= [ i for i in range( 5 ) if 0 == ( i % 2 ) ]
a
# ... this is the same as ...
= []
a for i in range( 5 ):
if 0 == ( i % 2 ):
a.append( i )
Tried with: Python 3.2