Adding elements to tuple in python

Append Element to a Tuple in Python

How to append an element to a tuple in python? Tuple in Python is a fundamental data structure that allows you to store multiple values in a single object. A tuple is an ordered and immutable (cannot update elements in a tuple) collection of items.

You can append an element or multiple elements to a tuple in Python by using many ways, for example, using the tuple() , concatenation + operator, and inserting elements in a tuple. In this article, I will explain appending elements to a tuple by using all these methods with examples.

1. Quick Examples of Appending Element to a Tuple

If you are in a hurry, below are some quick examples of how to append to a tuple.

 # Quick examples of append to a tuple # Example 1: Use concatenation + operator # To append to a tuple tuple1 = ('Spark', 'Python') tuple2 = ('Pandas', 'Java') tuple3 = tuple1 + tuple2 # Example 2: Use + operator tuple1 = ('Python', 'Java') tuple2 = ('C++', 'Oracle') + tuple1 + ('Pandas', 'Spark') # Example 3: Inserting elements in a tuple tuples = (15, 42, 73, 122) lst = list(tuples) lst.insert(1, 90) result = tuple(lst) 

2. Initialize a Tuple in Python

To initialize a tuple in Python, you can use () and separate the elements with comma . For example,

 # Initialize a tuple in python mytuple = (0, 1, 2, 3, 4, 5) 

Here is another example of initializing a tuple with four values of different data types and a nested tuple. This creates a tuple called my_tuple that contains four elements: an integer value 2 , a string Sparkbyexamples , a float 5.24 , and a nested tuple containing two integers (( 7, 9 )).

 # Initialize a tuple with four values my_tuple = (2, "Sparkbyexamples", 5.24, (7, 9)) print(my_tuple) # Output: # (2, 'Sparkbyexamples', 5.24, (7, 9)) 

You can also use the built-in tuple() function in Python to convert a list into a tuple. For example, mylist is a list that contains five elements, and the result is a tuple that contains the same elements as mylist . The tuple() function takes a single argument, which should be a list, and returns a tuple containing the same elements in the same order as the original list.

 # Convert a list into a tuple mylist = [2, 4, 6, 8, 10] result = tuple(mylist) print(result) # Output: # (2, 4, 6, 8, 10) 

3. Append Element to Tuple in Python

To append a single element to a tuple in Python use the + operator, To append a single element, you need to have an element as a tuple. When using a single element, you have to use (element,). Missing comma will get you an error.

 # Initialize tuple tuple1 = (10,20) print("tuple1: ",tuple1) # Append element to tuple tuple2 = tuple1 + (30,) print("tuple2: ",tuple2) # Output: # tuple1: (10, 20) # tuple2: (10, 20, 30) 

4. Append Multiple Elements to a Tuple

You can also append multiple elements to a tuple in Python using the concatenation «+» operator. You can use the «+» operator to join the tuple together in the order you want them to appear in the new tuple. For example, let’s create a tuple tuple1 and tuple2 , and then append them using the + operator to create a new tuple tuple3 .

 # Using + operator to append elements to tuple tuple1 = ('Spark', 'Python') tuple2 = ('Pandas', 'Java') print("tuple1: ",tuple1) print("tuple2: ",tuple2) # Append elements to tuple tuple3 = tuple1 + tuple2 print("tuple3 After Append: ",tuple3) 

This example yields the below output.

python append element tuple

Here’s another approach to append/concatenating tuples.

 # Use + operator # append to a tuple tuple1 = ('Python', 'Java') tuple2 = ('C++', 'Oracle') + tuple1 + ('Pandas', 'Spark') print(tuple2) # Output : # ('C++', 'Oracle', 'Python', 'Java', 'Pandas', 'Spark') 

5. Inserting Elements in a Tuple

In case you wanted to append or insert an element at a specific index of the tuple, you need to convert the tuple to a list and use the insert() method to insert the element and convert it back to a tuple using tuple(). For example, the below example inserts an element at the second position, you can directly specify the index 1 , as it refers to the second position.

 # Initialize tuple tuples = (15, 42, 73, 122) # Convert to list lst = list(tuples) # Add items by using insert() lst.insert(1, 90) # Convert list to a tuple(). result = tuple(lst) print(result) print(type(result)) # Output: # (15, 90, 42, 73, 122) #

6. Appending List to Tuple.

Sometimes you would be required to append list elements to a tuple, but this is not possible using the + operator as you can only concatenate a tuple (not “list”) to a tuple.

 tuples = (15, 42, 73, 122) tuples2 = tuples + [1, 2, 3] # Gets below error # Traceback (most recent call last): # File "/Users/admin/untitled6.py", line 12, in # tuples2 = tuples + [1, 2, 3] # TypeError: can only concatenate tuple (not "list") to tuple 

To overcome this convert list to a tuple using list().

 # This convert list to a tuple using list(). tuples = (15, 42, 73, 122) tuples2 = tuples + tuple([1, 2, 3]) 

Conclusion

In this article, I have explained how to append single and multiple elements to a tuple in python by using the tuple() , concatenation + operator, and inserting elements at a specific index in a tuple with examples.

References

You may also like reading:

Источник

How to append elements in Python tuple?

Tuples in Python are immutable, meaning that once they are created, their contents cannot be changed. However, there are situations when we want to change the existing tuple, in which case we must make a new tuple using only the changed elements from the original tuple.

Following is the example of the tuple −

Following is the output of the above code −

Tuple is immutable, although you can use the + operator to concatenate several tuples. The old object is still present at this point, and a new object is created.

Append elements in Tuple

Tuple is immutable, although you can use the + operator to concatenate several tuples. The old object is still present at this point, and a new object is created.

Example

Following is an example to append the tuple −

s=(2,5,8) s_append = s + (8, 16, 67) print(s_append) print(s)

Output

Following is an output of the above code −

Note− Concatenation is only possible with tuples. It can’t be concatenated to other kinds, such lists.

Example

Following is an example of concatenating a tuple with a list −

s=(2,5,8) s_append = (s + [8, 16, 67]) print(s_append) print(s)

Output

The following error came as an output of the above code −

Traceback (most recent call last): File "main.py", line 2, in s_append = (s + [8, 16, 67]) TypeError: can only concatenate tuple (not "list") to tuple 

Concatenating Tuple with one element

You can concatenate a tuple with one element if you want to add an item to it.

Example

Following is an example to concatenate a tuple with one element −

s=(2,5,8) s_append_one = s + (4,) print(s_append_one)

Output

Following is an output of the above code.

Note − The end of a tuple with only one element must contain a comma as seen in the above example.

Adding/Inserting items in a Tuple

You can concatenate a tuple by adding new items to the beginning or end as previously mentioned; but, if you wish to insert a new item at any location, you must convert the tuple to a list.

Example

Following is an example of adding items in tuple −

s= (2,5,8) # Python conversion for list and tuple to one another x = list(s) print(x) print(type(x)) # Add items by using insert () x.insert(5, 90) print(x) # Use tuple to convert a list to a tuple (). s_insert = tuple(x) print(s_insert) print(type(s_insert))

Output

we get the following output of the above code.

[2, 5, 8] ⁢class 'list'> [2, 5, 8, 90] (2, 5, 8, 90) ⁢class 'tuple'>

Using append() method

A new element is added to the end of the list using the append() method.

Example

Following is an example to append an element using append() method −

# converting tuple to list t=(45,67,36,85,32) l = list(t) print(l) print(type(l)) # appending the element in a list l.append(787) print(l) # Converting the list to tuple using tuple() t=tuple(l) print(t)

Output

Following is an output of the above code

[45, 67, 36, 85, 32] ⁢class 'list'> [45, 67, 36, 85, 32, 787] (45, 67, 36, 85, 32, 787)

Источник

Python Tuple : Append , Insert , Modify & delete elements in Tuple

In this article we will discuss how to Append, Insert, Replace and Delete elements from a tuple in python.

In Python, tuples are immutable i.e. once created we can not change its contents. But sometimes we want to modify the existing tuple, in that case we need to create a new tuple with updated elements only from the existing tuple.
Let’s see how to insert, modify and delete the elements from tuple.

Append an element in Tuple at end

Suppose we have a tuple i.e.

# Create a tuple tupleObj = (12 , 34, 45, 22, 33 )

Now to append an element in this tuple, we need to create a copy of existing tuple and then add new element to it using + operator i.e.

Frequently Asked:

# Append 19 at the end of tuple tupleObj = tupleObj + (19 ,)

We will assign the new tuple back to original reference, hence it will give an effect that new element is added to existing tuple.
Contents of tuple will be now,

A new Element is appended at the end of tuple.

Insert an element at specific position in tuple

To insert an element at a specific index in the existing tuple we need to create a new tuple by slicing the existing tuple and copying contents from it.

Suppose we have a tuple i.e.

# Create a tuple tupleObj = (12 , 34, 45, 22, 33 )

As indexing starts from 0 in tuple, so to insert an element at index n in this tuple, we will create two sliced copies of existing tuple from (0 to n) and (n to end) i.e.

# Sliced copy containing elements from 0 to n-1 tupleObj[ : n] # Sliced copy containing elements from n to end tupleObj[n : ]

Now join these two sliced copies with new elements in between i.e.

n = 2 # Insert 19 in tuple at index 2 tupleObj = tupleObj[ : n ] + (19 ,) + tupleObj[n : ]

Now contents of tuple will be.

A new Element is inserted at index n.

Modify / Replace the element at specific index in tuple

To replace the element at index n in tuple we will use the same slicing logic as above, but we will slice the tuple from from (0 to n-1) and (n+1 to end) i.e.

# Sliced copy containing elements from 0 to n-1 tupleObj[ : n] # Sliced copy containing elements from n to end tupleObj[n + 1 : ]

None of the above sliced copies contains existing element at index n. Now join these two sliced copies with new elements in between i.e.

tupleObj = (12, 34, 19, 45, 22, 33, 19) n = 2 # Replace the element at index 2 to 'Test' tupleObj = tupleObj[ : n] + ('test' ,) + tupleObj[n + 1 : ]

Now contents of tuple will be.

Element in index n is replaced now.

Delete an element at specific index in tuple

To delete the element at index n in tuple we will use the same slicing logic as above, but we will slice the tuple from from (0 to n-1) and (n+1 to end) i.e.

# Sliced copy containing elements from 0 to n-1 tupleObj[ : n] # Sliced copy containing elements from n to end tupleObj[n + 1 : ]

None of the above sliced copies contains existing element at index n. Now join these two sliced copies i.e.

tupleObj =(12, 34, 'test', 45, 22, 33, 19) n = 2 # Delete the element at index 2 tupleObj = tupleObj[ : n ] + tupleObj[n+1 : ]

Now contents of tuple will be.

Element in index n is deleted now.

Complete example is as follows,

def main(): # Create a tuple from list by type casting tupleObj = (12 , 34, 45, 22, 33 ) print("****** Append an element in Tuple at end ******") print("Original Tuple : ", tupleObj) # Append 19 at the end of tuple tupleObj = tupleObj + (19 ,) print("Modified Tuple : ", tupleObj) print("******* Insert an element at specific index in tuple *******") print("Original Tuple : ", tupleObj) n = 2 # Insert 19 in tuple at index 2 tupleObj = tupleObj[ : n] + (19 ,) + tupleObj[n : ] print("Modified Tuple : ", tupleObj) print("******* Modify / Replace the element at specific index in tuple *******") print("Original Tuple : ", tupleObj) n = 2 # Replace the element at index 2 to 'Test' tupleObj = tupleObj[ : n] + ('test' ,) + tupleObj[n + 1 : ] print("Modified Tuple : ", tupleObj) print("******* Delete the element at specific index in tuple *******") print("Original Tuple : ", tupleObj) n = 2 # Delete the element at index 2 tupleObj = tupleObj[ : n ] + tupleObj[n+1 : ] print("Modified Tuple : ", tupleObj) if __name__ == '__main__': main()
****** Append an element in Tuple at end ****** Original Tuple : (12, 34, 45, 22, 33) Modified Tuple : (12, 34, 45, 22, 33, 19) ******* Insert an element at specific index in tuple ******* Original Tuple : (12, 34, 45, 22, 33, 19) Modified Tuple : (12, 34, 19, 45, 22, 33, 19) ******* Modify / Replace the element at specific index in tuple ******* Original Tuple : (12, 34, 19, 45, 22, 33, 19) Modified Tuple : (12, 34, 'test', 45, 22, 33, 19) ******* Delete the element at specific index in tuple ******* Original Tuple : (12, 34, 'test', 45, 22, 33, 19) Modified Tuple : (12, 34, 45, 22, 33, 19)

Источник

Читайте также:  Использование javascript при создании страницы
Оцените статью