Example 1: Create a List using normal for loop and list comprehension
# Using for loop
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
# Code Description:
# - Create an empty list of squares
# - Loop through the range of 10
# - Append the square of the number to the squares list
# - Print the squares list
# Using list comprehension
squares = [i**2 for i in range(10)]
print(squares)
# Code Description:
# - Create a list of squares with the square of the number in the range of 10
# - Print the squares list
Example 2: List comprehension with if condition
# Using for loop
square_of_evens = []
for i in range(10):
if i % 2 == 0:
square_of_evens.append(i**2)
print(square_of_evens)
# Code Description:
# - Create an empty list of squares
# - Loop through the range of 10
# - Check if the number is even
# - Append the square of the number to the squares list
# - Print the squares list
# Using list comprehension
square_of_evens = [i**2 for i in range(10) if i % 2 == 0]
print(square_of_evens)
# Code Description:
# - Create a list of squares with the square of the number in the range of 10 if the number is even
# - Print the squares list
Example 3: List comprehension with multiple conditions
# Using for loop
square_of_evens = []
for i in range(10):
if i % 2 == 0 and i % 3 == 0:
square_of_evens.append(i**2)
print(square_of_evens)
# Code Description:
# - Create an empty list of squares
# - Loop through the range of 10
# - Check if the number is even and divisible by 3
# - Append the square of the number to the squares list
# - Print the squares list
# Using list comprehension
square_of_evens = [i**2 for i in range(10) if i % 2 == 0 and i % 3 == 0]
print(square_of_evens)
# Code Description:
# - Create a list of squares with the square of the number in the range of 10 if the number is even and divisible by 3
# - Print the squares list
Example 4: List comprehension with nested loops
# Using for loop
pairs = []
for i in range(2):
for j in range(2):
pairs.append((i, j))
print(pairs)
# Code Description:
# - Create an empty list pairs
# - Loop through the range of 2
# - Loop through the range of 2
# - Append the tuple of the numbers to the pairs list
# - Print the pairs list
# Using list comprehension
pairs = [(i, j) for i in range(2) for j in range(2)]
print(pairs)
# Code Description:
# - Create a list pairs with the tuple of the numbers in the range of 2
# - Print the pairs list
Example 5: Multiple Lists to Single List using List Comprehension
pairs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Using for loop
merged = []
for pair in pairs:
for num in pair:
merged.append(num)
print(merged)
# Code Description:
# - Create an empty list merged
# - Loop through the list of pairs
# - Loop through the numbers in the pair
# Using list comprehension
merged = [num for pair in pairs for num in pair]
print(merged)
# Code Description:
# - Create a list merged with the numbers in the pairs list
# - Print the merged list