Simple List Comprehension
Create a list of numbers from 1 to 5 using list comprehension. Result should be: [1, 2, 3, 4, 5] Print the list.
List comprehensions create lists in one line.
Basic syntax:
[expression for item in iterable]
Examples:
# Create list of squares
squares = [x * x for x in range(5)]
# Result: [0, 1, 4, 9, 16]
# Double each number
numbers = [1, 2, 3]
doubled = [n * 2 for n in numbers]
# Result: [2, 4, 6]
# With condition (filter)
even = [x for x in range(10) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8]
Create a list of numbers from 1 to 5 using list comprehension. Result should be: [1, 2, 3, 4, 5] Print the list.
Create a list of squares for numbers 1 to 5. Result: [1, 4, 9, 16, 25] Print the list.
Create a list of even numbers from 1 to 10. Use list comprehension with if condition. Result: [2, 4, 6, 8, 10] Print the list.
Given: words = ["hello", "world", "python"] Create a new list with all words in uppercase. Use list comprehension with .upper() Result: ["HELLO", "WORLD"…