list comprehension in python

main.py
# List comprehension in Python is a concise way to create lists. 
# It follows the syntax: [expression for item in iterable if condition]

# Example 1: Creating a list of squares of numbers from 0 to 9
squares = [i**2 for i in range(10)]
print(squares)

# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Example 2: Creating a list of even numbers from 0 to 9
evens = [i for i in range(10) if i % 2 == 0]
print(evens)

# Output: [0, 2, 4, 6, 8]
444 chars
15 lines

related categories

gistlibby LogSnag