Append a range to a list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 20, 2022

banner

Photo from Unsplash

Append a range to a list in Python #

Use the list.extend() method to append a range to a list in Python, e.g. my_list.extend(range(2)). The extend method takes an iterable (such as a range) and extends the list by appending all of the items from the iterable.

main.py
my_list = ['a', 'b'] my_list.extend(range(2)) print(my_list) # 👉️ ['a', 'b', 0, 1] # ------------------------------- # 👇️ if you have to convert range to list 👇️ l = list(range(0, 3)) print(l) # 👉️ [0, 1, 2] l.append(3) print(l) # 👉️ [0, 1, 2, 3] l.extend([4, 5]) print(l) # 👉️ [0, 1, 2, 3, 4, 5]

We used th extend() method to append a range to a list.

The list.extend method takes an iterable (such as a list or a range) and extends the list by appending all of the items from the iterable.

main.py
my_list = ['a', 'b'] my_list.extend(['c', 'd', 'e']) print(my_list) # 👉️ ['a', 'b', 'c', 'd', 'e']

The list.extend method returns None as it mutates the original list.

If you use the append() method, you would add a single item to the list.

main.py
my_list = ['a', 'b'] my_list.append(range(2)) print(my_list) # 👉️ ['a', 'b', range(0, 2)]

The list.append() method adds an item to the end of the list.

If you want to add a nested list to the list, use the list() class to convert the range object to a list.

main.py
my_list = ['a', 'b'] my_list.append(list(range(2))) print(my_list) # 👉️ ['a', 'b', [0, 1]]

If you need to append items to a range object, convert the range object to a list first.

main.py
l = list(range(0, 3)) print(l) # 👉️ [0, 1, 2] l.append(3) print(l) # 👉️ [0, 1, 2, 3] l.extend([4, 5]) print(l) # 👉️ [0, 1, 2, 3, 4, 5]

Range objects don't have an append or extend methods, so we have to convert the object to a list before using the methods.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.