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()
.
>>> 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]