
Syntax: List Range and Concatenation
Finding list ranges and combining lists.
Python allows you to create lists using a built-in function called range(), and combine or concatenate two lists using the + operator. Both of these operations are crucial in data processing and manipulation tasks in Python.
List Range
The range() function generates a sequence of numbers within a given range. You can convert this range into a list using the list() function.
numbers = list(range(1, 11))
print(numbers)
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List Concatenation
The + operator can be used to combine or concatenate two lists into one.
numbers_2 = list(range(11, 21))
all_numbers = numbers + numbers_2
print(all_numbers)
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Practice: Generate List of Even Numbers
-
Create a list named
even_numbersand initialize it with even numbers from2to20usingrange(). -
Print the
even_numberslist.
Run your code and confirm that the output is a list of even numbers from 2 to 20.
HINT*: Click here for a hint
> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
SOLUTION*: Click here for an example solution
even_numbers = list(range(2, 21, 2))
print(even_numbers)
Practice: Combine Two Lists
-
Create a list
odd_numberswith odd numbers from1to20. -
Concatenate
even_numbersandodd_numbersinto a listall_numbers. -
Print the
all_numberslist.
Run your code and confirm that the output is a combined list of even and odd numbers from 1 to 20.
HINT*: Click here for a hint
> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
SOLUTION*: Click here for an example solution
odd_numbers = list(range(1, 20, 2))
all_numbers = even_numbers + odd_numbers
print(all_numbers)
Nice work! These operations allow for efficient manipulation of lists in Python, which is particularly useful when working with large data sets.