Append a Range to a List in Python

# Append a Range to a List in Python

Python has a built-in method, called range(start, stop), that allows you to easily create arrays whose values are integers, starting from start and ending before stop (exclusive). The following code creates a list of integers from 0 to 9:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Providing only one argument to the range() method will create a list of integers from 0 to the value of the argument given.

Oftentimes you'll want to create a range and add it to the end of a list. In order to do this, you'll want to use the list's extend() method, which takes an iterable of values, like a list, and adds them to the end of the target list.

Here you can see an example of adding a list to the end of another list using extend().

## Get free courses, guided projects, and more

>>> list_a = [1, 2, 3]
>>> list_b = [4, 5, 6]
>>> list_a.extend(list_b)
>>> list_a
[1, 2, 3, 4, 5, 6]


Finally, to create a range and add it to the end of a list, you would do something very similar to the code above, but using the range() method instead of a predefined list:

>>> my_list = [1, 2, 3]
>>> my_list.extend(range(4, 7))
>>> my_list
[1, 2, 3, 4, 5, 6]


You'll commonly see that the return value of the range method is wrapped in a list. This is because range doesn't actually return a list, but instead an object that implements the collections.abc.Sequence methods. While this object is iterable and list-like, it's best practice to explicitly convert it to a list before using it.

Note that since Python lists are not typed, you can add a range to any list, regardless of what values it contains. For example:

>>> my_list = ['hello', 'world']
>>> my_list.extend(range(3))
>>> my_list
['hello', 'world', 0, 1, 2]

Last Updated: July 1st, 2022
Project

### Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
Details
Project

### Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

Details