Lists: Exercises


4. List Comprehension. In Python, a list comprehension is a concise way to create lists. It allows you to generate a new list by applying an expression to each item in an existing list or range.

For example, you can create a list of squares of numbers from 1 to 5 using list comprehension: squares = [x**2 for x in range(1, 6)].

Note that the range(start, end) creates a list of numbers of between start and end-1.

Use a list comprehension to create a list of the numbers 1 to 100.


# Use list comprehension to create a list of the numbers from 1 to 100. numbers = ___ # Print the list of numbers. print(___) # Use list comprehension to create a list of the numbers from 1 to 100. numbers = [x for x in range(1, 101)] # Print the list of numbers. print(numbers) test_object("numbers") success_msg("Correct! You can also think of a list comprehension as another way of writing a loop in Python.")
A list comprehension allows you to generate a new list based on an expression and a condition.

Previous Exercise Next Exercise