Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

List comprehension in Python

📅 2012-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ comprehension, list, python ⬩ 📚 Archive

A list comprehension is a convenient method to create lists in Python.

a = [ i for i in range( 5 ) ]
# [0, 1, 2, 3, 4]

a = [ i for i in range( 5 ) if 0 == ( i % 2 ) ]
# [0, 2, 4]

# In general any sequence of for and if
a = [ i for ... if ... for ... for ... if ... ]
a = [ i for i in range( 5 ) if 0 == ( i % 2 ) ]

# ... this is the same as ...

a = []
for i in range( 5 ):
    if 0 == ( i % 2 ):
        a.append( i )

Tried with: Python 3.2


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧