Python change tuple item

Python — Update Tuples

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.

But there are some workarounds.

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Example

Convert the tuple into a list to be able to change it:

x = («apple», «banana», «cherry»)
y = list(x)
y[1] = «kiwi»
x = tuple(y)

Add Items

Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.

Читайте также:  What is javascript cgi

Example

Convert the tuple into a list, add «orange», and convert it back into a tuple:

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:

Example

Create a new tuple with the value «orange», and add that tuple:

thistuple = («apple», «banana», «cherry»)
y = («orange»,)
thistuple += y

Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple.

Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:

Example

Convert the tuple into a list, remove «apple», and convert it back into a tuple:

Or you can delete the tuple completely:

Example

The del keyword can delete the tuple completely:

thistuple = («apple», «banana», «cherry»)
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Источник

Update tuples in Python (Add, change, remove items in tuples)

In Python, tuples are immutable, meaning that you cannot modify them directly, such as adding, changing, or removing items (elements). If you need to work with mutable data, use lists instead. However, if you must update a tuple, you can convert it to a list, perform the required modifications, and then convert it back to a tuple.

Note that even though terms like «add», «change», and «remove» are used for simplicity, a new object is created in reality, and the original object remains unchanged.

Tuples are immutable

Consider the following example of a tuple:

t = (0, 1, 2) print(t) # (0, 1, 2) print(type(t)) # 

To access elements in a tuple, you can use indexing [] or slicing [:] , similar to lists.

Since tuples are immutable, you cannot assign a new value to an element.

# t[0] = 100 # TypeError: 'tuple' object does not support item assignment 

Destructive methods (= methods that modify the original object), such as append() in lists, are not available in tuples.

# t.append(100) # AttributeError: 'tuple' object has no attribute 'append' 

Append an item to a tuple

Although tuples are immutable, you can concatenate them using the + operator. In this process, the original object remains unchanged, and a new object is created.

t = (0, 1, 2) t_add = t + (3, 4, 5) print(t_add) # (0, 1, 2, 3, 4, 5) print(t) # (0, 1, 2) 

Only tuples can be concatenated, not other data types like lists.

# print(t + [3, 4, 5]) # TypeError: can only concatenate tuple (not "list") to tuple 

You can concatenate a list to a tuple by first converting the list to a tuple using tuple() .

print(t + tuple([3, 4, 5])) # (0, 1, 2, 3, 4, 5) 

tuple() can only convert iterable objects, such as lists, to tuples. Integers ( int ) and floating-point numbers ( float ) cannot be converted.

# print(t + tuple(3)) # TypeError: 'int' object is not iterable 

To append an item to a tuple, concatenate it as a single-element tuple.

Remember that a single-element tuple requires a trailing comma.

Add/insert items to a tuple

To add new items at the beginning or end of a tuple, use the + operator as mentioned earlier. However, to insert a new item at any position, you must first convert the tuple to a list.

Convert a tuple to a list using list() .

t = (0, 1, 2) l = list(t) print(l) # [0, 1, 2] print(type(l)) # 

Insert an item using insert() .

l.insert(2, 100) print(l) # [0, 1, 100, 2] 

Convert the list back to a tuple with tuple() .

t_insert = tuple(l) print(t_insert) # (0, 1, 100, 2) print(type(t_insert)) # 

Change items in a tuple

You can change items in a tuple using the same approach. Convert the tuple to a list, update it, and then convert it back to a tuple.

t = (0, 1, 2) l = list(t) l[1] = 100 t_change = tuple(l) print(t_change) # (0, 100, 2) 

Remove items from a tuple

Similarly, you can remove items from a tuple using the same method.

t = (0, 1, 2) l = list(t) l.remove(1) t_remove = tuple(l) print(t_remove) # (0, 2) 

In the above example, remove() is used, but you can also use pop() and del .

  • Convert pandas.DataFrame, Series and numpy.ndarray to each other
  • numpy.delete(): Delete rows and columns of ndarray
  • NumPy: Set whether to print full or truncated ndarray
  • nan (not a number) in Python
  • pandas: Get/Set element values with at, iat, loc, iloc
  • Determine, count, and list leap years in Python
  • Check Python version on command line and in script
  • Raw strings in Python
  • pandas: Handle strings (replace, strip, case conversion, etc.)
  • Get the n-largest/smallest elements from a list in Python
  • pandas: Delete rows, columns from DataFrame with drop()
  • How to return multiple values from a function in Python
  • Convert list and tuple to each other in Python
  • Generate random int/float in Python (random, randrange, randint, etc.)
  • NumPy: How to use reshape() and the meaning of -1

Источник

Python – Change Tuple Values

If you have gone through the tutorial – Python Tuples, you would understand that Python Tuples are immutable. Therefore, you cannot change values of Tuple items. But, there is a workaround.

In this tutorial, we will learn how to update or change tuple values with the help of lists.

The basic difference between a list and tuple in Python is that, list is mutable while tuple is immutable.

So, to change or update Tuple values, we shall convert our tuple to a list, update the required item and then change back the list to a tuple.

Examples

1. Update a Tuple item using a list

In this example, we have a Tuple. Following is the step by step process of what we shall do to the Tuple.

  1. We shall convert the tuple to a list.
  2. Update the required item of the list.
  3. Convert the list back to tuple and assign it to the original tuple.

Python Program

tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #update list list1[2] = 63 #change back list to tuple tuple1 = tuple(list1) print(tuple1)

2. Remove item from a given Tuple

In this example, we shall remove an item from the tuple, again using List.

Python Program

tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) #change tuple to list list1 = list(tuple1) #remove an item from list list1.remove(2) #change back list to tuple tuple1 = tuple(list1) print(tuple1)

Summary

In this tutorial of Python Examples, we learned how to work around to change the values of items in Python Tuple.

Источник

Python Program to Replace Elements in a Tuple

In this article, you will find out how to use Python to find the first and last elements of a tuple in this tutorial.

The quick response is that you can access the first and last elements of the tuple in Python using the index operator([]). The methods described here can be used to obtain your single tuple element.

Before diving in to the solution let us understand tuple in python.

What is tuple in Python?

A tuple is one of Python’s four built-in data types for storing data collections. The other three are list, set, and dictionary, each with a unique set of features and applications.

The elements of a tuple are immutable and ordered. We can create a tuple by specifying the elements within the round brackets separated by commas, as shown below –

Example

firstuple = ("apple", "banana", "cherry") print(firstuple)

Output

Following is the output of the above query –

Features of tuple in Python

Tuple items − Duplicate values are permitted for triple items, which are ordered and immutable. The first item in a triple has an index of [0], the second has an index of [1], and so on.

Ordered − When we say that a tuple is ordered, we are referring to the fact that the items are in a specific order that won’t change.

Unchangeable − Tuples are immutable, which means that once we create a tuple, we cannot change, add, or remove any of its components.

Replacing the elements in a tuple

Tuples are immutable i.e. once we create a tuple we cannot change their values. Therefore to change the elements in a tuple —

  • We’ll turn the tuple into a list.
  • Refresh the list’s necessary items.
  • Return the list to the tuple form, then assign it to the original tuple.

Example

Let us see an example for this. Here we are creating a tuple, converting it into a list and printing the results.

tuple1 = (1,2,3,4,5,6,7) list1 = list(tuple1) list1[5] = 9 tuple1 = tuple(list1) print(tuple1)

Output

Example

Now let us see the same example with sting values –

x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x)

Output

Deleting an element from a tuple

In order to remove an element from the beginning of a tuple, we will make a new tuple with the remaining elements as shown below.

myTuple = (11, 22, 33, 44, 55, 66, 77, 88) print("Original Tuple is:", myTuple) myTuple = myTuple[1:] print("Updated tuple is:", myTuple)

Output

Original Tuple is: (11, 22, 33, 44, 55, 66, 77, 88) The updated tuple is: (22, 33, 44, 55, 66, 77, 88)

Example

We can slice out the remaining elements of a tuple in the event that the last element needs to be removed.

myTuple = (1, 2, 3, 4, 5, 6, 7, 8) print("Original Tuple is:", myTuple) tupleLength = len(myTuple) myTuple = myTuple[0:tupleLength - 1] print("Updated tuple is:", myTuple)

Output

Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8) Updated tuple is: (1, 2, 3, 4, 5, 6, 7)

Example

To remove an element that is present at index «i». We will cut the original tuple into two slices, the initial slice will include each element in the initial tuple from index 0 to index i1.

The items from index «i 1» to last will be in the second tuple. Then, excluding the element at index «i,» we will concatenate the freshly created tuples as follows –

myTuple = (1, 2, 3, 4, 5, 6, 7, 8) print("Original Tuple is:", myTuple) left_tuple = myTuple[0:3] right_tuple = myTuple[4:] myTuple = left_tuple + right_tuple print("Updated tuple after deleting element at index 3 is:", myTuple)

Output

Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8) Updated tuple after deleting element at index 3 is: (1, 2, 3, 5, 6, 7, 8)

Modifying an element at a specific index

To modify element from an index we will make two slices of the original tuple to change the element at index «i» of the tuple.

The first slice will have components from the initial tuple’s index 0 to i-1. From index «i 1» to the last, the second slice will include all the components. The element at index «i» will then be updated by inserting the new value at the following position.

Example

myTuple = (9, 8, 7, 6, 5, 4, 3, 2, 1) print("Original Tuple is:", myTuple) left_tuple = myTuple[0:2] right_tuple = myTuple[5:] myTuple = left_tuple + (100,) + right_tuple print("Updated tuple after modifying element at index 3 is:", myTuple)

Output

Original Tuple is: (9, 8, 7, 6, 5, 4, 3, 2, 1) Updated tuple after modifying element at index 3 is: (9, 8, 100, 4, 3, 2, 1)

Источник

Оцените статью