Creating Lists with Number Ranges
One of the common tasks in Python programming is creating lists with a range of numbers. This can be achieved using the built-in range()
function.
The range()
function generates a sequence of numbers within a specified range. The basic syntax is:
range(start, stop, step)
start
: (optional) The starting number of the sequence (default is 0)
stop
: The ending number of the sequence (not included)
step
: (optional) The step size between each number (default is 1)
Here are some examples of using the range()
function to create lists:
## Create a list of numbers from 0 to 9
numbers = list(range(10))
print(numbers) ## Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
## Create a list of numbers from 5 to 10
numbers = list(range(5, 11))
print(numbers) ## Output: [5, 6, 7, 8, 9, 10]
## Create a list of even numbers from 2 to 20
even_numbers = list(range(2, 21, 2))
print(even_numbers) ## Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
## Create a list of numbers in descending order from 10 to 1
descending_numbers = list(range(10, 0, -1))
print(descending_numbers) ## Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
By using the range()
function and converting the result to a list, you can easily create lists with a range of numbers. This is a powerful technique that can be used in various programming tasks, such as iterating over a sequence of numbers, generating data for analysis, or creating dynamic content.
In the next section, we'll explore some practical applications of using lists with number ranges.