In Python, we can easily add a tuple to a list with the list extend() function.
list_of_numbers = [0, 1, 2, 3]
tuple_of_numbers = (4, 5)
list_of_numbers.extend(tuple_of_numbers)
print(list_of_numbers)
#Output:
[0, 1, 2, 3, 4, 5]
You can also use the += operator to append the items of a tuple to a list in Python.
list_of_numbers = [0, 1, 2, 3]
tuple_of_numbers = (4, 5)
list_of_numbers += tuple_of_numbers
print(list_of_numbers)
#Output:
[0, 1, 2, 3, 4, 5]
When working with collections of data in Python, the ability to add and remove elements from an object easily is very valuable.
We can easily append tuples to lists in our Python programs.
The Python extend() function allows us to append items of any iterable object onto a list.
With extend(), we can add a tuple to a list.
Below is a simple example in Python of how to add the items of a tuple to a list.
list_of_numbers = [0, 1, 2, 3]
tuple_of_numbers = (4, 5)
list_of_numbers.extend(tuple_of_numbers)
print(list_of_numbers)
#Output:
[0, 1, 2, 3, 4, 5]
Using += to Append Tuple to List in Python
You can also use the Python += operator to add tuple elements to a list. The += operator is most used when incrementing a variable but can also be used to append elements to lists.
Below is an example of how to use += to add a tuple to a list in Python.
list_of_numbers = [0, 1, 2, 3]
tuple_of_numbers = (4, 5)
list_of_numbers += tuple_of_numbers
print(list_of_numbers)
#Output:
[0, 1, 2, 3, 4, 5]
Hopefully this article has been useful for you to understand how to add a tuple to a list in Python.