TypeError: 'tuple' object does not support item assignment

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

# TypeError: 'tuple' object does not support item assignment

The Python "TypeError: 'tuple' object does not support item assignment" occurs when we try to change the value of an item in a tuple.

To solve the error, convert the tuple to a list, change the item at the specific index and convert the list back to a tuple.

typeerror tuple object does not support item assignment

Here is an example of how the error occurs.

We tried to update an element in a tuple, but tuple objects are immutable which caused the error.

# Convert the tuple to a list to solve the error

We cannot assign a value to an individual item of a tuple.

Instead, we have to convert the tuple to a list.

convert tuple to list to solve the error

This is a three-step process:

  • Use the list() class to convert the tuple to a list.
  • Update the item at the specified index.
  • Use the tuple() class to convert the list back to a tuple.

Once we have a list, we can update the item at the specified index and optionally convert the result back to a tuple.

Python indexes are zero-based, so the first item in a tuple has an index of 0 , and the last item has an index of -1 or len(my_tuple) - 1 .

# Constructing a new tuple with the updated element

Alternatively, you can construct a new tuple that contains the updated element at the specified index.

construct new tuple with updated element

The get_updated_tuple function takes a tuple, an index and a new value and returns a new tuple with the updated value at the specified index.

The original tuple remains unchanged because tuples are immutable.

We updated the tuple element at index 1 , setting it to Z .

If you only have to do this once, you don't have to define a function.

The code sample achieves the same result without using a reusable function.

The values on the left and right-hand sides of the addition (+) operator have to all be tuples.

The syntax for tuple slicing is my_tuple[start:stop:step] .

The start index is inclusive and the stop index is exclusive (up to, but not including).

If the start index is omitted, it is considered to be 0 , if the stop index is omitted, the slice goes to the end of the tuple.

# Using a list instead of a tuple

Alternatively, you can declare a list from the beginning by wrapping the elements in square brackets (not parentheses).

using list instead of tuple

Declaring a list from the beginning is much more efficient if you have to change the values in the collection often.

Tuples are intended to store values that never change.

# How tuples are constructed in Python

In case you declared a tuple by mistake, tuples are constructed in multiple ways:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

# Checking if the value is a tuple

You can also handle the error by checking if the value is a tuple before the assignment.

check if value is tuple

If the variable stores a tuple, we set it to a list to be able to update the value at the specified index.

The isinstance() function returns True if the passed-in object is an instance or a subclass of the passed-in class.

If you aren't sure what type a variable stores, use the built-in type() class.

The type class returns the type of an object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to convert a Tuple to an Integer in Python
  • How to convert a Tuple to JSON in Python
  • Find Min and Max values in Tuple or List of Tuples in Python
  • Get the Nth element of a Tuple or List of Tuples in Python
  • Creating a Tuple or a Set from user Input in Python
  • How to Iterate through a List of Tuples in Python
  • Write a List of Tuples to a File in Python
  • AttributeError: 'tuple' object has no attribute X in Python
  • TypeError: 'tuple' object is not callable in Python [Fixed]

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Solve Python TypeError: 'tuple' object does not support item assignment

python tuple does not support assignment

Consider the example below:

Solution #1: Change the tuple to list first

Solution #2: create a new tuple.

This tutorial shows you two easy solutions on how to change the tuple object element(s) and avoid the TypeError.

Take your skills to the next level ⚡️

python tuple does not support assignment

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python typeerror: ‘tuple’ object does not support item assignment Solution

Tuples are immutable objects . “Immutable” means you cannot change the values inside a tuple. You can only remove them. If you try to assign a new value to an item in a variable, you’ll encounter the “typeerror: ‘tuple’ object does not support item assignment” error.

In this guide, we discuss what this error means and why you may experience it. We’ll walk through an example of this error so you can learn how to solve it in your code.

Find your bootcamp match

Typeerror: ‘tuple’ object does not support item assignment.

While tuples and lists both store sequences of data, they have a few distinctions. Whereas you can change the values in a list, the values inside a tuple cannot be changed. Also, tuples are stored within parenthesis whereas lists are declared between square brackets.

Because you cannot change values in a tuple, item assignment does not work.

Consider the following code snippet:

This code snippet lets us change the first value in the “honor_roll” list to Holly. This works because lists are mutable. You can change their values. The same code does not work with data that is stored in a tuple.

An Example Scenario

Let’s build a program that tracks the courses offered by a high school. Students in their senior year are allowed to choose from a class but a few classes are being replaced.

Start by creating a collection of class names:

We’ve created a tuple that stores the names of each class being offered.

The science department has notified the school that psychology is no longer being offered due to a lack of numbers in the class. We’re going to replace psychology with philosophy as the philosophy class has just opened up a few spaces.

To do this, we use the assignment operator:

This code will replace the value at the index position 3 in our list of classes with “Philosophy”. Next, we print our list of classes to the console so that the user can see what classes are being actively offered:

Use a for loop to print out each class in our tuple to the console. Let’s run our code and see what happens:

Our code returns an error.

The Solution

We’ve tried to use the assignment operator to change a subject in our list. Tuples are immutable so we cannot change their values. This is why our code returns an error.

To solve this problem, we convert our “classes” tuple into a list . This will let us change the values in our sequence of class names.

Do this using the list() method:

We use the list() method to convert the value of “classes” to a list. We assign this new list to the variable “as_list”. Now that we have our list of classes stored as a list, we can change existing classes in the list.

Let’s run our code:

Our code successfully changes the “Psychology” class to “Philosophy”. Our code then prints out the list of classes to the console.

If we need to store our data as a tuple, we can always convert our list back to a tuple once we have changed the values we want to change. We can do this using the tuple() method:

This code converts “as_list” to a tuple and prints the value of our tuple to the console:

We could use this tuple later in our code if we needed our class names stored as a tuple.

The “typeerror: ‘tuple’ object does not support item assignment” error is raised when you try to change a value in a tuple using item assignment.

To solve this error, convert a tuple to a list before you change the values in a sequence. Optionally, you can then convert the list back to a tuple.

Now you’re ready to fix this error in your code like a pro !

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

CodeFatherTech

Learn to Code. Shape Your Future

Tuple Object Does Not Support Item Assignment. Why?

Have you ever seen the error “tuple object does not support item assignment” when working with tuples in Python? In this article we will learn why this error occurs and how to solve it.

The error “tuple object does not support item assignment” is raised in Python when you try to modify an element of a tuple. This error occurs because tuples are immutable data types. It’s possible to avoid this error by converting tuples to lists or by using the tuple slicing operator.

Let’s go through few examples that will show you in which circumstances this error occurs and what to do about it.

Let’s get started!

Explanation of the Error “Tuple Object Does Not Support Item Assignment”

Define a tuple called cities as shown below:

If you had a list you would be able to update any elements in the list .

But, here is what happens if we try to update one element of a tuple:

Tuples are immutable and that’s why we see this error.

There is a workaround to this, we can:

  • Convert the tuple into a list.
  • Update any elements in the list.
  • Convert the final list back to a tuple.

To convert the tuple into a list we will use the list() function :

Now, let’s update the element at index 1 in the same way we have tried to do before with the tuple:

You can see that the second element of the list has been updated.

Finally, let’s convert the list back to a tuple using the tuple() function :

Makes sense?

Avoid the “Tuple Object Does Not Support Item Assignment” Error with Slicing

The slicing operator also allows to avoid this error.

Let’s see how we can use slicing to create a tuple from our original tuple where only one element is updated.

We will use the following tuple and we will update the value of the element at index 2 to ‘Rome’.

Here is the result we want:

We can use slicing and concatenate the first two elements of the original tuple, the new value and the last two elements of the original tuple.

Here is the generic syntax of the slicing operator (in this case applied to a tuple).

This takes a slice of the tuple including the element at index n and excluding the element at index m .

Firstly, let’s see how to print the first two and last two elements of the tuple using slicing…

First two elements

We can also omit the first zero considering that the slice starts from the beginning of the tuple.

Last two elements

Notice that we have omitted index m considering that the slice includes up to the last element of the tuple.

Now we can create the new tuple starting from the original one using the following code:

(‘Rome’,) is a tuple with one element of type string.

Does “Tuple Object Does Not Support Item Assignment” Apply to a List inside a Tuple?

Let’s see what happens when one of the elements of a tuple is a list.

If we try to update the second element of the tuple we get the expected error:

If we try to assign a new list to the third element…

…once again we get back the error “‘ tuple’ object does not support item assignment “.

But if we append another number to the list inside the tuple, here is what happens:

The Python interpreter doesn’t raise any exceptions because the list is a mutable data type.

This concept is important for you to know when you work with data types in Python:

In Python, lists are mutable and tuples are immutable.

How to Solve This Error with a List of Tuples

Do we see this error also with a list of tuples?

Let’s say we have a list of tuples that is used in a game to store name and score for each user:

The user John has gained additional points and I want to update the points associated to his user:

When I try to update his points we get back the same error we have seen before when updating a tuple.

How can we get around this error?

Tuples are immutable but lists are mutable and we could use this concept to assign the new score to a new tuple in the list, at the same position of the original tuple in the list.

So, instead of updating the tuple at index 0 we will assign a new tuple to it.

Let’s see if it works…

It does work! Once again because a list is mutable .

And here is how we can make this code more generic?

Ok, this is a bit more generic because we didn’t have to provide the name of the user when updating his records.

This is just an example to show you how to address this TypeError , but in reality in this scenario I would prefer to use a dictionary instead.

It would allow us to access the details of each user from the name and to update the score without any issues.

Tuple Object Does Not Support Item Assignment Error With Values Returned by a Function

This error can also occur when a function returns multiple values and you try to directly modify the values returned by the function.

I create a function that returns two values: the number of users registered in our application and the number of users who have accessed our application in the last 30 days.

As you can see the two values are returned by the function as a tuple.

So, let’s assume there is a new registered user and because of that I try to update the value returned by the function directly.

I get the following error…

This can happen especially if I know that two values are returned by the function but I’m not aware that they are returned in a tuple.

Why Using Tuples If We Get This Error?

You might be thinking…

What is the point of using tuples if we get this error every time we try to update them?

Wouldn’t be a lot easier to always use lists instead?

We can see the fact that tuples are immutable as an added value for tuples when we have some data in our application that should never be modified.

Let’s say, for example, that our application integrates with an external system and it needs some configuration properties to connect to that system.

The tuple above contains two values: the API endpoint of the system we connect to and the port for their API.

We want to make sure this configuration is not modified by mistake in our application because it would break the integration with the external system.

So, if our code inadvertently updates one of the values, the following happens:

Remember, it’s not always good to have data structures you can update in your code whenever you want.

In this article we have seen when the error “tuple object does not support item assignment” occurs and how to avoid it.

You have learned how differently the tuple and list data types behave in Python and how you can use that in your programs.

If you have any questions feel free to post them in the comment below 🙂

Claudio Sabato is an IT expert with over 15 years of professional experience in Python programming, Linux Systems Administration, Bash programming, and IT Systems Design. He is a professional certified by the Linux Professional Institute .

With a Master’s degree in Computer Science, he has a strong foundation in Software Engineering and a passion for robotics with Raspberry Pi.

Related posts:

  • Python TypeError: int object is not iterable: What To Do To Fix It?
  • Python Unexpected EOF While Parsing: The Way To Fix It
  • Python AttributeError: Fix This Built-in Exception
  • Understand the “str object is not callable” Python Error and Fix It!

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

  • Privacy Overview
  • Strictly Necessary Cookies

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

Tech With Tech

How to Solve ‘Tuple’ Object Does Not Support Item Assignment (Python)

Here’s everything about TypeError: ‘Tuple’ Object Does Not Support Item Assignment in Python.

You’ll learn:

  • The specifics of the tuple data type
  • The difference between immutable and mutable data types
  • How to change immutable data types

So if you want to understand this error in Python and how to solve it, then you’re in the right place.

Let’s jump right in!

  • IndentationError: Unexpected Unindent in Python
  • How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python)
  • SyntaxError: Invalid Character in Identifier: How to Solve? (Python)
  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed (Python)
  • 9 Examples of Unexpected Character After Line Continuation Character (Python)

Mutable, or Immutable? That Is the Question

Data types in Python are mutable or immutable .

All data types that are numeric , for example, are immutable . 

You can write something like this:

Have you changed the variable a ? 

Not really: When you write a = 1 , you put the object 1 in memory and told the name a to refer to this literal. 

Next, when you write a = a + 1 , Python evaluates the expression on the right:

Python takes the object referred by a (the 1 ) and then adds 1 to it. 

You get a new object, a 2 . This object goes right into the memory and a references instead of object 1 . 

The value of object 1 has not changed—it would be weird if 1 would out of a sudden a 2 , for example, wouldn’t it? So instead of overwriting an object ( 1 ), a new object ( 2 ) is created and assigned to the variable ( a ).

Mutable Data Types

More complex data types in Python are sequences such as: 

  • Byte Arrays

Sequences contain several values, which can be accessed by index.

Software developer standing near his desk while working in a hurry.

However, some sequences are mutable (byte arrays, lists) , while others are immutable (tuples) . 

You can create a tuple and access its elements like this:

Yet if you try to change one of the elements, you get an error:

Notice that the item in the tuple at index 2 is a list. You can change the list without changing the tuple:

The object stored in the tuple remains the same, but its contents have changed. But what if you still need to change the element in the tuple?

You can do this by converting the tuple to a list. Then you change the element, and then convert the list to a tuple again:

For large amounts of data, conversion operations can take quite a long time:

As you can see, for a list of 100 million float numbers, this operation takes about a second. This is not a long time for most tasks, but it is still worth considering if you are dealing with large amounts of data.

However, there is another way to “change” a tuple element—you can rebuild a tuple using slicing and concatenation:

Note that it is necessary to put a comma in parentheses to create a tuple of one element. If you use just parentheses, then (‘uno’) is not a tuple, but a string in parentheses . 

Concatenating a string with a tuple is not possible:

Interestingly, you can use shorthand operators on a tuple, like this:

Or even like this:

3 Examples of TypeError: ‘Tuple’ Object Does Not Support Item Assignment in Python

Let’s look at some practical examples of when this error can occur. The simplest is when you initially enter the sequence incorrectly:

In this example, the name list1 refers to a tuple despite the list in the name. The name does not affect the type of variable. To fix this error, simply change the parentheses to square brackets in the constructor:

Perhaps you have a list with some values, such as the student’s name and grade point average:

Alice did a poor job this semester, and her GPA dropped to 90:

Unfortunately, you cannot just change the average score in such a list. You already know that you can convert a tuple to a list, or form a new tuple. For example, like this:

However, if you need to change values regularly, it makes sense to switch from a list of tuples to a dictionary. Dictionaries are a perfect fit for such tasks. You can do this easily with the dict() constructor:

Now you can change the average by student name:

#1 Real World Example of TypeError: ‘Tuple’ Object Does Not Support Item Assignment in Python

An interesting example of a novice programmer trying to enter values in a list from the keyboard using the eval() function:

This method is not very reliable by itself.

Even if the user enters the correct sequence separated by commas—for example, 3, 2, 4, 1 —it will be evaluated in a tuple. 

Naturally, an attempt to assign a new value to a tuple element in the line list[i +1] = list[i] raises a TypeError: ‘tuple’ object does not support item assignment . 

Here, you see another mistake—which, by the way, may even be invisible during program execution. 

The my_sort function uses the list data type name as the argument name. This is not only the name of the data type, but also the list constructor. 

Python will not throw an error while executing this code, but if you try to create a list using the constructor inside the my_sort function, you will have big problems.

Programmer trying to solve problems with the code he's working on.

In this case, to enter elements into the list, it would be more correct to read the entire string and then split it using the split() method. If you need integer values, you can also apply the map() function, then convert the resulting map object into a list:

The construction looks a little cumbersome, but it does its job. You can also enter list items through a list comprehension:

You can choose the design that you like best.

#2 Real World Example of TypeError: ‘Tuple’ Object Does Not Support Item Assignment in Python

Another example of when a TypeError: ‘tuple’ object does not support item assignment may occur is the use of various libraries. 

If you have not studied the documentation well enough, you may not always clearly understand which data type will be returned in a given situation. In this example, the author tries to make the picture redder by adding 20 to the red color component:

This produces an error on the line pixel[0] = pixel[0] + 20 . How?

You are converting pixels to a list in line of code 3 . Indeed, if you check the type of the pixels variable, you get a list:

However, in the loop, you iterate over the pixels list elements, and they already have a different type. Check the type of the pixels list element with index 0 :

And this is a tuple!

So, you can solve this problem by converting lists to tuples inside a loop, for example.

However, in this case, you will need to slightly adjust the iterable value. This is because you will need the pixel color values and the index to write the new values into the original array. 

For this, use the enumerate() function:

The program will work successfully with that version of a loop, and you will get a redder image at the output. It would be more correct to trim values above 255 , for example:

But if the program consists only of this transformation, then Python will already truncate the values when saving the image.

Here’s more Python support:

  • 9 Examples of Unexpected Character After Line Continuation Character
  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
  • How to Solve SyntaxError: Invalid Character in Identifier
  • ImportError: Attempted Relative Import With No Known Parent Package
  • IndentationError: Unexpected Unindent in Python (and 3 More)

Theresa McDonough

Tech entrepreneur and founder of Tech Medic, who has become a prominent advocate for the Right to Repair movement. She has testified before the US Federal Trade Commission and been featured on CBS Sunday Morning, helping influence change within the tech industry.

The Research Scientist Pod

How to Solve Python TypeError: ‘tuple’ object does not support item assignment

by Suf | Programming , Python , Tips

Tuples are immutable objects, which means you cannot change them once created. If you try to change a tuple in place using the indexing operator [], you will raise the TypeError: ‘tuple’ object does not support item assignment.

To solve this error, you can convert the tuple to a list, perform an index assignment then convert the list back to a tuple.

This tutorial will go through how to solve this error and solve it with the help of code examples.

Table of contents

Typeerror: ‘tuple’ object does not support item assignment.

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.

The part 'tuple' object tells us that the error concerns an illegal operation for tuples.

The part does not support item assignment tells us that item assignment is the illegal operation we are attempting.

Tuples are immutable objects, which means we cannot change them once created. We have to convert the tuple to a list, a mutable data type suitable for item assignment.

Let’s look at an example of assigning items to a list. We will iterate over a list and check if each item is even. If the number is even, we will assign the square of that number in place at that index position.

Let’s run the code to see the result:

We can successfully do item assignments on a list.

Let’s see what happens when we try to change a tuple using item assignment:

We throw the TypeError because the tuple object is immutable.

To solve this error, we need to convert the tuple to a list then perform the item assignment. We will then convert the list back to a tuple. However, you can leave the object as a list if you do not need a tuple.

Let’s run the code to see the updated tuple:

Congratulations on reading to the end of this tutorial. The TypeError: ‘tuple’ object does not support item assignment occurs when you try to change a tuple in-place using the indexing operator [] . You cannot modify a tuple once you create it. To solve this error, you need to convert the tuple to a list, update it, then convert it back to a tuple.

For further reading on TypeErrors, go to the article:

  • How to Solve Python TypeError: ‘str’ object does not support item assignment

To learn more about Python for data science and machine learning, go to the  online courses page on Python  for the most comprehensive courses available.

Have fun and happy researching!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

TypeError: ‘tuple’ object does not support item assignment: How to Fix

Avatar

Have you ever tried to assign a value to a specific element of a tuple in Python, only to get an error message like “TypeError: ‘tuple’ object does not support item assignment”? If so, you’re not alone. This is a common error that can be confusing for beginners, but it’s actually pretty easy to understand once you know what’s going on.

In this article, we’ll take a closer look at what a tuple is, why you can’t assign values to individual elements of a tuple, and how you can work around this limitation. We’ll also provide some examples of how to use tuples effectively in your Python code.

So if you’re ready to learn more about tuples and how to avoid the “TypeError: ‘tuple’ object does not support item assignment” error, keep reading!

| Column 1 | Column 2 | Column 3 | |—|—|—| | Error | `TypeError: ‘tuple’ object does not support item assignment` | An error that occurs when you try to assign a value to an item in a tuple. | | Cause | The cause of this error is that tuples are immutable, which means that you cannot change their values after they have been created. | | Solution | To fix this error, you can either convert the tuple to a list, or you can use a different data type, such as a dictionary or a set. |

A TypeError is a type of error that occurs when an operation is attempted on an object of an incorrect type. For example, trying to assign a value to an element of a tuple will result in a TypeError.

This error can be avoided by ensuring that the objects you are working with are of the correct type. For example, if you want to assign a value to an element of a tuple, you can use the `append()` method to add the value to the end of the tuple.

**What causes a TypeError?**

A TypeError can be caused by a number of things, including:

  • Trying to use an operator that is not supported for the given type of object.
  • Trying to access an element of an object that does not exist.
  • Trying to assign a value to an object that is immutable.

**Trying to use an operator that is not supported for the given type of object**

One common cause of a TypeError is trying to use an operator that is not supported for the given type of object. For example, the `+` operator can be used to add two numbers together, but it cannot be used to add a string to a number.

python >>> 1 + ‘2’ TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

To avoid this type of error, make sure that you are using the correct operators for the types of objects you are working with.

**Trying to access an element of an object that does not exist**

Another common cause of a TypeError is trying to access an element of an object that does not exist. For example, the following code will result in a TypeError because the `index` 0 does not exist in the `list` `my_list`:

python >>> my_list = [‘a’, ‘b’, ‘c’] >>> my_list[0] ‘a’ >>> my_list[1] ‘b’ >>> my_list[2] ‘c’ >>> my_list[3] Traceback (most recent call last): File “ “, line 1, in IndexError: list index out of range

To avoid this type of error, make sure that you are checking the index of the element you are trying to access before you try to access it.

**Trying to assign a value to an object that is immutable**

Finally, a TypeError can also be caused by trying to assign a value to an object that is immutable. An immutable object is an object whose value cannot be changed after it has been created. For example, strings and numbers are immutable objects.

python >>> my_string = ‘hello’ >>> my_string[0] = ‘j’ Traceback (most recent call last): File “ “, line 1, in TypeError: ‘str’ object does not support item assignment

To avoid this type of error, make sure that you are not trying to assign a value to an immutable object.

A TypeError is a type of error that occurs when an operation is attempted on an object of an incorrect type. This error can be avoided by ensuring that the objects you are working with are of the correct type and that you are not trying to access elements of an object that do not exist or assign values to immutable objects.

Here are some additional tips for avoiding TypeErrors:

  • Use the `type()` function to check the type of an object before you try to perform an operation on it.
  • Use the `len()` function to check the length of a list or tuple before you try to access an element that is out of range.
  • Use the `isinstance()` function to check whether an object is of a particular type.

By following these tips, you can help to avoid TypeErrors in your code.

What is a TypeError?

A TypeError occurs when you try to use an operator or function on an object that does not support it. For example, you cannot use the `+` operator to add two strings together, because strings are immutable.

How to fix a TypeError?

To fix a TypeError, you need to identify the cause of the error and correct it. This may involve:

  • Using the correct operator for the given type of object.
  • Checking that the object you are trying to access exists.
  • Using a different type of object that is mutable.

Examples of TypeErrors

Here are some examples of TypeErrors:

>>> tuple = (1, 2, 3) >>> tuple[0] = 4 TypeError: ‘tuple’ object does not support item assignment

>>> list = [1, 2, 3] >>> list[0] = ‘4’ TypeError: can’t convert ‘int’ object to str implicitly

>>> dict = {‘a’: 1, ‘b’: 2} >>> dict[‘c’] = 3 KeyError: ‘c’

In the first example, we try to assign the value 4 to the first element of the tuple `tuple`. However, tuples are immutable, which means that their values cannot be changed. This results in a TypeError.

In the second example, we try to convert the integer 1 to a string and assign it to the first element of the list `list`. However, the `int` type cannot be converted to the `str` type implicitly. This results in a TypeError.

In the third example, we try to access the key `c` in the dictionary `dict`. However, the key `c` does not exist in the dictionary. This results in a KeyError.

TypeErrors can be avoided by using the correct operators and functions for the given type of object. It is also important to check that the object you are trying to access exists before trying to access it.

If you are still getting TypeErrors, you can try using a different type of object that is mutable. For example, if you are trying to add two strings together, you can use the `join()` method to join the two strings into one.

Here are some additional resources that you may find helpful:

  • [Python TypeErrors](https://docs.python.org/3/library/exceptions.htmltypeerror)
  • [How to Fix Python TypeErrors](https://www.w3schools.com/python/python_errors_typeerror.asp)

A: This error occurs when you try to assign a value to an item in a tuple. Tuples are immutable, which means that their values cannot be changed after they are created. Therefore, you cannot use the assignment operator (=) to assign a new value to an item in a tuple.

Q: How can I avoid this error? A: There are a few ways to avoid this error.

  • Use a list instead of a tuple. Lists are mutable, which means that their values can be changed after they are created. Therefore, you can use the assignment operator (=) to assign new values to items in a list.
  • Use the slice operator ([]) to access items in a tuple. The slice operator allows you to access a range of items in a tuple. This can be useful if you need to change multiple items in a tuple at once.
  • Use the `tuple()` function to create a new tuple with the desired values. This can be useful if you need to create a tuple with the same values as an existing tuple, but with the ability to change the values later.

Q: Can I still use tuples if I need to be able to change their values? A: Yes, you can still use tuples if you need to be able to change their values. However, you will need to use a different data structure, such as a list or a dictionary.

Q: What are some other common errors related to tuples? A: Some other common errors related to tuples include:

  • Trying to access an item in a tuple that does not exist. This will result in a `KeyError` exception.
  • Trying to add an item to a tuple. This will result in a `TypeError` exception.
  • Trying to delete an item from a tuple. This will result in a `TypeError` exception.

Q: Where can I learn more about tuples? A: You can learn more about tuples by reading the following resources:

  • [The Python Tutorial: Tuples](https://docs.python.org/3/tutorial/datastructures.htmltuples)
  • [Stack Overflow: Tuples](https://stackoverflow.com/questions/tagged/tuples)

We hope that this blog post has been helpful. If you have any other questions about tuples or this error, please feel free to leave a comment below.

Here are some key takeaways from this blog post:

  • A tuple is a collection of immutable objects, while a list is a collection of mutable objects.
  • When you try to assign a value to an element of a tuple, you will get a TypeError: ‘tuple’ object does not support item assignment.
  • To get around this error, you can use list comprehension or the tuple() function.
  • For more information on tuples, please see the Python documentation.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

How to fix the no module named ‘pygame’ error.

Have you ever encountered the dreaded “no module named ‘pygame’” error? If so, you’re not alone. This error is a common one for Python programmers who are trying to use the pygame library. In this article, we’ll take a look at what causes this error and how you can fix it. We’ll start by discussing…

ModuleNotFoundError: No module named ‘tensorflow.contrib’

ModuleNotFoundError: No module named ‘tensorflow.contrib’ If you’re a Python developer who’s ever tried to import the `tensorflow.contrib` module, you’ve probably encountered the dreaded `ModuleNotFoundError: No module named ‘tensorflow.contrib’`. This error can be a real pain, especially if you’re not sure what’s causing it or how to fix it. In this article, we’ll take a look…

How to Fix the ‘No Module Named ‘azure” Error

Have you ever tried to import the `azure` module into your Python script, only to be met with an error message saying “No module named ‘azure’”? If so, you’re not alone. This is a common problem that can be caused by a number of different factors. In this article, we’ll take a look at some…

AttributeError: module ‘aiobotocore’ has no attribute ‘aiosession’

AttributeError: module ‘aiobotocore’ has no attribute ‘aiosession’ This error message is a common one for Python developers who are trying to use the `aiobotocore` library. The `aiobotocore` library is a Python wrapper for the Amazon Web Services (AWS) Boto3 API. It provides a high-level interface for interacting with AWS services using asynchronous programming. The `aiosession`…

Unimplemented type ‘list’ in ‘encodeelement’: How to fix this error

Unimplemented Type ‘List’ in ‘EncodeElement’ The `encodeElement` function in the Go standard library is used to encode a Go value into a JSON string. However, there is a known issue with this function where it does not support encoding values of type `list`. This can cause problems when trying to encode data that contains lists,…

AttributeError: module ‘cv2’ has no attribute ‘xfeatures2d’

AttributeError: module ‘cv2’ has no attribute ‘xfeatures2d’ If you’re a Python developer working with computer vision, you’ve probably come across this error at some point. It’s a common problem, and it can be frustrating to figure out what’s causing it. In this article, we’ll take a look at what this error means, why it happens,…

GuidingCode

How to Fix the Error “Cannot Set Headers After They are Sent to the Client” in JavaScript?

How to Fix the “Type 'Null' Is Not Assignable to Type 'String'”?

How to Fix “Type ‘Null’ Is Not Assignable to Type ‘String’” in TypeScript?

How to fix Java Package Does Not Exist

How to Fix the Java “Package Does Not Exist” Error?

Recent posts.

python tuple does not support assignment

How to Fix “ReferenceError: Variable Is Not Defined” in JavaScript?

  • WooCommerce
  • Webpack warning

How to Fix “TypeError: Tuple Does Not Support Item Assignment” in Python?

' src=

Did you assign a tuple to a new value and get the TypeError: tuple does not support item assignment in Python?

If you’re working with Python and you encounter the “TypeError: ‘tuple’ does not support item assignment” error, it means that you are trying to change the value of an element within a tuple, which is not possible.

When we try to update the value of an item in a tuple, Python throws the error TypeError: ‘tuple’ object does not support item assignment . Tuples are immutable data types, hence assigning a tuple to a variable or data causes the TypeError exception . Transforming tuples to lists or slicing them, can be helpful in preventing the TypeError: ‘tuple’ object does not support item assignment .

Furthermore, you can convert the tuple to a list, to make the necessary changes, and then convert the list back to a tuple to fix the problem. 

In this article, we’ll discuss the TypeError: tuple object does not support item assignment in Python, why it occurs, and how to fix ⚒️it. So without further ado, let’s dive deep into the topic. Let’s go over a few examples that will show this error’s causes and possible solutions.

Table of Contents

Why does the typeerror:  tuple does not support item assignment error occur, how to fix typeerror: ‘tuple’ object does not support item assignment in python, 1. assigning a value to the index, 2. with the use of slice operator, 3. apply list inside a tuple.

As we’ve discussed in Python, when we try to assign a new value to a tuple that causes TypeError:  tuple object does not support item assignment. Let’s see an example 👇

TypeError: Tuple Does Not Support Item Assignment in Python

See the above example; we have created a tuple Tuple_1 and assigned values. Then we assigned “Kelvin” at index 2 of Tuple and print the tuple that gives the TypeError:  tuple does not support item assignment as we are trying to assign a value to an already created tuple.

As we have seen in the above example, we have created a tuple and assigned a value, we can convert the tuple into a list, and then we can assign values to it. To convert a tuple into a list, we utilized the list() class. In the above example, we have assigned 1. 

To fix the error first we have to change the tuple to a list: we have three different alternate solutions.

  • Assigning a Value to the Index
  • With the Use of Slice Operator
  • Apply List Inside a Tuple

We have to convert Convert the tuple into a list by using a list function and then assigning a value at any index of a list that will update any elements in the list. The final step is to convert 

final list back to a tuple as shown in the following example.

In the above example, we have converted the tuple to a list, assigned “Sofia” at the index on the list, and again converted the list to a tuple and printed it.

This “Type error: tuple object does not support item assignment” can also be avoided using the slicing operator. Let’s look at how we can slice our original tuple to get a new one after omitting some elements of the tuple. You can also add an element to any index after in  the tuple using the slice operator.

If one element in a tuple is listed, only on that particular index we can assign another element. But if we assign an element at the index of an element that is not a list it will generate a “Type error: tuple object does not support item assignment.” Let’s see what happens when a tuple has a list as one of its elements.

To summarize the article on how to fix the TypeError: tuple does not support item assignment , we’ve discussed why it occurs and how to fix it. Furthermore, we’ve seen that the three approaches that help fix the TypeError: ‘tuple’ object do not support item assignment , including Assigning a value to the index, With the use of slice Operator, Applying a list inside a tuple

Let’s have a quick recap of the topics discussed in this article.

  • Why does the TypeError: ‘tuple’ object does not support item assignment occurs?
  • How to fix the TypeError TypeError: tuple does not support item assignment in Python?
  • Assigning a value to the index.
  • With the use of slice Operator.
  • Apply List inside a Tuple.

If you’ve found this article helpful, don’t forget to share and comment below 👇 which solutions have helped you solve the problem.

Happy Coding!

' src=

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Related Posts

TabError-inconsistent-use-of-tabs-and-spaces-in-indentation-

How to Fix “TabError: Inconsistent Use of Tabs And Spaces in Indentation” in Python?

What is Multiple Inheritance in Python?

What is Multiple Inheritance in Python?

Learn how to slice a dataframe in Pandas

How to Slice a Dataframe in Pandas?

How to Fix "Could Not Find a Version That Satisfies the Requirement"?

How to Fix “Could Not Find a Version That Satisfies the Requirement X”?

  • Travel & Tourism
  • Beauty & Fashion

Logo

If you’re a Python programmer, you’ve probably come across the “tuple object does not support item assignment” error before. This error can be frustrating, especially if you’re not sure why you’re getting it in the first place. In this blog post, we’ll take a look at what causes this error and how you can fix it.

The “tuple object does not support item assignment” error occurs when you try to modify a tuple that is immutable (i.e., cannot be altered). Tuples cannot be changed because they are designed to be used as data structures that hold information that should not be modified. For example, if you have a tuple that contains a person’s name and address, you would not want to be able to modify that person’s name or address without changing the tuple itself.

That’s why trying to modify a tuple using item assignment (i.e., using square brackets [] to select an element within the tuple and then using the = operator to assign a new value to that element) will result in an error. If you need to modify the elements within a tuple, you can do so by creating a new tuple with the modified values.

How to solve the error for tuple object does not support item assignment?

This error means that you’re trying to modify a value in a tuple, but tuples are unchangable. This means that you can’t change any values inside them after they’ve been created. There are two ways to fix this error.

  • First, you can convert the tuple to a list, make your changes to the list, and then convert it back into a tuple.
  • Second, you can create a new tuple with the values that you want to change.

For example, if you have a tuple with the values (1, 2, 3) and you want to modify the second value to 4, you could do either of the following: my_list = list(my_tuple) my_list[1] = 4 my_tuple = tuple(my_list) my_tuple = (1, 4, 3) As you can see, both approaches achieve the same result. However, the second approach is generally simpler and less error-prone.

Does the tuple object support item assignment?

The answer to this question is a bit complicated. The tuple object does not support item assignment, meaning that you cannot reassign a value to a specific index within a tuple. However, you can replace an entire tuple with another tuple, as long as the new tuple has the same number of elements. For example, if you have a tuple with three elements, you could replace it with a new three-element tuple. This is sometimes called “shallow” assignment, because only the top-level object is being replaced; the individual items within the tuple are not being mutated. While this may not be precisely what you were asking, it’s the closest thing to item assignment that tuples support.

In conclusion, the “tuple object does not support item assignment” error occurs when you attempts to modify an immutable tuple. To fix this error, you can create a new tuple with the modified values.

Logo

Ever felt like you’re wrestling with a locked suitcase when trying to grasp the concept of tuples in Python? You’re not alone.

Tuples, just like a tightly locked suitcase, are immutable in Python, meaning once you’ve packed them, you can’t change what’s inside. They can hold a collection of items, but once created, they remain constant.

So, why use them, and how? This comprehensive guide will walk you through everything you need to know about Python tuples, from basic use to advanced techniques. So, let’s unlock the suitcase and dive into the fascinating world of Python tuples.

TL;DR: What is a Tuple in Python?

A tuple in Python is an immutable sequence type. It’s like a list that cannot be changed once created. Here’s a simple example of a tuple:

In the example above, we created a tuple named ‘my_tuple’ with three elements. Once created, you can’t add or remove elements from ‘my_tuple’ or change the existing elements. This immutability makes tuples a useful tool in Python programming, especially when you want to ensure certain data remains constant.

If you’re intrigued and want to unlock more about tuples, including their advanced usage, keep reading!

Table of Contents

Getting Started with Python Tuples

Advanced tuple techniques, exploring alternatives to tuples, navigating tuple troubles, delving into python immutability, expanding tuple usage in larger projects, further resources and readings, python tuples: a quick recap.

Tuples in Python are incredibly straightforward to create. You simply define your tuple by enclosing your items, separated by commas, within parentheses () . Here’s an example of a basic Python tuple:

In the above code, we’ve created a tuple named fruit_tuple that contains three elements. When we print fruit_tuple , we get the output ('apple', 'banana', 'cherry') , which is the tuple we defined.

One of the key characteristics of tuples is their immutability, i.e., once a tuple is created, you cannot change its content. This is advantageous when you have a set of data that should not be altered.

However, this immutability can also be a pitfall if you’re not careful. For instance, if you try to change an item in the tuple like this:

You’ll encounter a TypeError . Python is telling us that tuples do not support item assignment, which is a fancy way of saying you can’t change their content once they’re created.

Python tuples offer more than just a static collection of items. They can be used in more complex ways, such as tuple unpacking, nested tuples, and as dictionary keys. Let’s explore these advanced uses.

Tuple Unpacking

Tuple unpacking allows you to assign the elements of a tuple to different variables. This can be handy when you want to extract values from a tuple in a single line. Here’s how it works:

In the above code, we’ve assigned each item in the fruit_tuple to a separate variable ( fruit1 , fruit2 , fruit3 ). When we print these variables, we get the individual elements of the tuple.

Nested Tuples

Tuples can hold other tuples within them, creating what we call ‘nested tuples’. This is useful when you want to group related data together. Here’s an example:

In this example, nested_tuple contains two tuples, each with two elements.

Tuples as Dictionary Keys

Because of their immutability, tuples can be used as keys in Python dictionaries, unlike lists. This is advantageous when you need a composite key, i.e., a key that is made up of multiple parts. Here’s an example:

Here, we’ve used tuples as keys in our fruit_colors dictionary. When we print the value associated with the key ('apple', 'banana') , we get ‘yellow’.

While tuples are powerful and versatile data structures in Python, they aren’t the only game in town. Python offers other data structures such as lists and dictionaries. Understanding these alternatives can help you make informed decisions about which data structure to use based on your specific needs.

Lists: The Mutable Alternative

Lists in Python are similar to tuples, but unlike tuples, they are mutable. This means you can add, remove, or change elements in a list after it’s created. Here’s an example of a Python list:

In the above code, we created a list and then changed the first element from ‘apple’ to ‘orange’. This would not be possible with a tuple. While this mutability provides flexibility, it may not be ideal when you want to ensure certain data remains constant.

Dictionaries: Key-Value Pairs

Dictionaries in Python are a collection of key-value pairs. They are mutable like lists but provide a way to associate pieces of related information. Here’s an example:

In the above code, we created a dictionary where each fruit (key) is associated with a color (value). This association is something unique to dictionaries and can’t be achieved with tuples or lists.

While tuples, lists, and dictionaries each have their own advantages, the best choice depends on your specific needs. If you need immutability, go with tuples. If you need to change the data, lists are your best bet. And if you need to associate values, dictionaries are the way to go.

While working with Python tuples, you may encounter some common errors or obstacles. Let’s explore these issues and their solutions, along with some best practices for optimization.

Attempting to Modify a Tuple

One of the most common errors when working with tuples is trying to modify them. Remember, tuples are immutable. Let’s see what happens when we try to change a tuple:

The above code returns a TypeError because we’re trying to change a tuple, which is not allowed in Python. If you need a collection of items that can be modified, consider using a list instead.

Unpacking a Tuple Incorrectly

Another common issue arises when trying to unpack more or fewer variables than the tuple contains. Here’s an example:

In this case, Python throws a ValueError because we’re trying to unpack a three-item tuple into only two variables. To solve this, ensure the number of variables matches the number of items in the tuple.

Best Practices and Optimization

When working with tuples, it’s good practice to use them for collections of items that are not meant to change. This clearly signals to anyone reading your code that those values should remain constant. For larger collections of items, tuples can be more memory-efficient than lists, making your programs more optimized. Remember, the right data structure can make your code both easier to read and more efficient.

Immutability is a fundamental concept in Python that directly impacts how we work with tuples. But what does it really mean for a data structure to be immutable, and why is it so important?

In Python, an immutable object is an object whose state cannot be changed after it’s created. This means that once you’ve defined an immutable object, such as a tuple, you can’t add, remove, or change its elements. Let’s see this in action:

In the above code, Python throws a TypeError when we try to change an element in the tuple. This is Python’s way of enforcing immutability.

The Importance of Immutability

Immutability is important for a couple of reasons. First, it provides a degree of safety. When you define a tuple, you can be sure its data will remain constant throughout the program, preventing accidental modifications.

Second, immutability makes Python tuples hashable, meaning they can be used as dictionary keys, unlike lists. This is a powerful feature when you need a composite key, i.e., a key made up of multiple parts.

Beyond Tuples: Other Immutable Types

Tuples aren’t the only immutable objects in Python. Other immutable types include integers, floats, strings, and frozensets. Like tuples, these types can’t be changed after they’re created, providing the same benefits of safety and hashability.

Python tuples, with their immutability and ability to hold multiple data types, can be incredibly useful in larger scripts or projects. For instance, they can be used to group related data together, making your code cleaner and more organized.

Consider a scenario where you’re building a script to manage a database of students. Each student could be represented as a tuple, with elements for their name, age, and grade level.

In this example, the tuple student holds related pieces of data together in a logical and organized way.

Complementary Data Structures

Tuples often work hand-in-hand with other data structures. For instance, lists of tuples are a common sight in Python code. This combination allows you to have an ordered collection of immutable data.

In this example, students is a list of tuples, each representing a different student.

For more advanced usage, you can explore how tuples interact with dictionaries, sets, and other Python data structures.

For a deeper dive into the previously mentioned topics, and more, check out the following guides:

  • Python Data Types Logic: Simplified – Explore boolean data type usage in Python to enhance your logical reasoning skills.

Python Set Intersection: Usage Guide with Examples – Dive into set intersection operations in Python for finding common elements between sets.

Exploring Bisect Module in Python – Learn how to use bisect in Python for binary search and insertion into sorted collections.

Python Sets – Detailed guides on Python sets by Real Python.

Python’s Official Data Structures Documentation – Understanding Python’s data structures from official sources.

Python Dictionaries Tutorial – Comprehensive guide to Python dictionaries by W3Schools.

Python tuples, with their immutability and ability to hold multiple data types, are a powerful tool in Python’s data structure toolkit. They provide safety and efficiency, especially when working with data that should remain constant.

Here’s a quick comparison of tuples with other Python data structures:

Data StructureMutableUse Case
TupleNoGrouping related, constant data
ListYesGrouping related, changeable data
DictionaryYesAssociating related key-value pairs

To summarize, tuples are best used when you need to group related data that should remain constant. They can be used in more advanced ways, such as tuple unpacking, nested tuples, and as dictionary keys. However, when you need to change the data or associate values, lists and dictionaries may be more suitable.

Remember, Python will throw a TypeError if you try to modify a tuple, and a ValueError if you try to unpack more or fewer variables than the tuple contains. To avoid these issues, ensure you understand the concept of immutability and use the right number of variables when unpacking a tuple.

Tuples often work hand-in-hand with other data structures, particularly in larger scripts or projects. To expand your knowledge, explore how tuples interact with dictionaries, sets, and other Python data structures.

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Sorting a dictionary by value in Python sorted key-value pairs arrows code

Python TypeError: 'tuple' object does not support item assignment Solution

Posted in PROGRAMMING LANGUAGE /   PYTHON

Python TypeError: 'tuple' object does not support item assignment Solution

Vinay Khatri Last updated on September 19, 2024

Table of Content

In Python, we have a built-in data structure " tuple " which is similar to a Python list and stores elements in sequential order. The only difference between a Python list and a tuple is that the tuple is an immutable data structure, which means once a tuple object is defined, we can not change its elements. If we try to change the tuple elements using indexing and assignment operator, we will receive the TypeError: 'tuple' object does not support item assignment Error.

In this Python guide, we will discuss this error in detail and learn how to debug it. We will also walk through a common example to demonstrate this error. So without further ado, let's get started with the Error statement.

Python Error: TypeError: 'tuple' object does not support item assignment

The Error Statement TypeError: 'tuple' object does not support item assignment is divided into two parts Exception Type and Error Message.

  • TypeError (Exception Type)
  • 'tuple' object does not support item assignment (Error Message)

1. TypeError

TypeError is a standard Python exception. It is raised in a Python program when we try to perform an invalid or unsupported operation on a Python object.

2. 'tuple' object does not support item assignment

This error message tells us that the tuple object does not support new value assignment to its elements. You will only encounter this error message when you try to change the values of a tuple element using indexing.

Although we can use indexing to access the individual tuple elements, we can not use indexing to change tuple element values.

Here we are getting this error because in line 5, we are trying to assign a new value to the tuple " letters ". As tuple does not support element change operation, it throws the error when we try to assign a new value to the tuple element. Now let's discuss a common scenario example, and in the solution, we will see an alternative way to debug this problem and add and change the value of a tuple element using some logic.

Common Example Scenario

Tuples are faster as compared to the Python list. That's why many Python developers use tuples to store items or element values. Although tuple supports element access using indexing, it throws an error when changing its elements. This is also one of the main reasons why many pythoneer use tuples instead of lists when they do not want to change the elements of the container throughout the program.

But let's say you come across a situation when you want to change the element value of a tuple, then what would you do?

Here we will discuss an example where we first try to change one of the values of a tuple using indexing. Then in the solution, we will discuss how we can achieve it.

Break the code

The error statement is quite expected. We know that when we try to change the tuple element value using indexing, we get the error. In line 5, we tried to change the first element of the tuple " sem_1_subjects " from "Java" to "Python" , which is the cause of this error statement.

When we use the tuple element as a container to store elements, we think of that container as intact throughout the program. But in the case when we come across a situation where we need to change the value of the tuple elements, there we first need to convert that tuple object to a list using list() function. Then only we can change its values. After changing the value, we can convert back the list object to the tuple using tuple() function.

Example solution

In this Python tutorial, we discussed the "TypeError: 'tuple' object does not support item assignment" Error in detail. This error raises in a Python program when we try to change the value of a tuple element using the assignment operator. A tuple is an immutable data structure, and once we define all its elements, we can not change them. To change its elements, first, need to convert the tuple object to a list, and then only we can change its values.

If you are still getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.

People are also reading:

  • Python typeerror: ‘str’ object is not callable Solution
  • Python SyntaxError: can’t assign to function call Solution
  • Python TypeError: ‘method’ object is not subscriptable Solution
  • Python typeerror: list indices must be integers or slices, not str Solution
  • Python NameError name is not defined Solution
  • Python typeerror: ‘list’ object is not callable Solution
  • Python IndexError: tuple index out of range Solution
  • Python AttributeError: 'numpy.ndarray' object has no attribute 'append' Solution
  • Python typeerror: string indices must be integers Solution
  • Python TypeError: ‘float’ object is not callable Solution

Vinay

Vinay Khatri I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Related Blogs

7 Most Common Programming Errors Every Programmer Should Know

7 Most Common Programming Errors Every Programmer Should Know

Every programmer encounters programming errors while writing and dealing with computer code. They m…

Carbon Programming Language - A Successor to C++

Carbon Programming Language - A Successor to C++

A programming language is a computer language that developers or programmers leverage to …

Introduction to Elixir Programming Language

Introduction to Elixir Programming Language

We know that website development is at its tipping point, as most businesses aim to go digital nowa…

Leave a Comment on this Post

Python's tuple Data Type: A Deep Dive With Examples

Python's tuple Data Type: A Deep Dive With Examples

Table of Contents

Getting Started With Python’s tuple Data Type

Creating tuples through literals, using the tuple() constructor, accessing items in a tuple: indexing, retrieving multiple items from a tuple: slicing, exploring tuple immutability, packing and unpacking tuples, returning tuples from functions, creating copies of a tuple, concatenating tuples together, repeating the content of a tuple, reversing a tuple with reversed(), reversing a tuple with the slicing operator, sorting a tuple with sorted(), using a for loop to iterate over a tuple, using a comprehension or a generator expression to traverse tuples, finding items in a tuple, getting the length of a tuple, comparing tuples, common gotchas of python tuples, tuples with named fields: collections.namedtuple, tuples with named fields and type hints: typing.namedtuple, data classes: dataclasses.dataclass, deciding whether to use tuples.

In Python, a tuple is a built-in data type that allows you to create immutable sequences of values. The values or items in a tuple can be of any type. This makes tuples pretty useful in those situations where you need to store heterogeneous data, like that in a database record, for example.

Through this tutorial, you’ll dive deep into Python tuples and get a solid understanding of their key features and use cases. This knowledge will allow you to write more efficient and reliable code by taking advantage of tuples.

In this tutorial, you’ll learn how to:

  • Create tuples in Python
  • Access the items in an existing tuple
  • Unpack , return , copy , and concatenate tuples
  • Reverse , sort , and traverse existing tuples
  • Explore other features and common gotchas of tuples

In addition, you’ll explore some alternative tools that you can use to replace tuples and make your code more readable and explicit.

To get the most out of this tutorial, you should have a good understanding of a few Python concepts, including variables , functions , and for loops . Familiarity with other built-in data structures , especially lists , is also a plus.

Get Your Code: Click here to download the free sample code that shows you how to write more readable code with tuples in Python.

The built-in tuple data type is probably the most elementary sequence available in Python. Tuples are immutable and can store a fixed number of items. For example, you can use tuples to represent Cartesian coordinates (x, y) , RGB colors (red, green, blue) , records in a database table (name, age, job) , and many other sequences of values.

In all these use cases, the number of elements in the underlying tuple is fixed , and the items are unchangeable . You may find several situations where these two characteristics are desirable. For example, consider the RGB color example:

Once you’ve defined red , then you won’t need to add or change any components. Why? If you change the value of one component, then you won’t have a pure red color anymore, and your variable name will be misleading. If you add a new component, then your color won’t be an RGB color. So, tuples are perfect for representing this type of object.

Note: Throughout this tutorial, you’ll find the terms items , elements , and values used interchangeably to refer to the objects stored in a tuple.

Some of the most relevant characteristics of tuple objects include the following:

  • Ordered : They contain elements that are sequentially arranged according to their specific insertion order.
  • Lightweight : They consume relatively small amounts of memory compared to other sequences like lists.
  • Indexable through a zero-based index : They allow you to access their elements by integer indices that start from zero.
  • Immutable : They don’t support in-place mutations or changes to their contained elements. They don’t support growing or shrinking operations.
  • Heterogeneous : They can store objects of different data types and domains, including mutable objects.
  • Nestable : They can contain other tuples, so you can have tuples of tuples.
  • Iterable : They support iteration, so you can traverse them using a loop or comprehension while you perform operations with each of their elements.
  • Sliceable : They support slicing operations, meaning that you can extract a series of elements from a tuple.
  • Combinable : They support concatenation operations, so you can combine two or more tuples using the concatenation operators, which creates a new tuple.
  • Hashable : They can work as keys in dictionaries when all the tuple items are immutable.

Tuples are sequences of objects. They’re commonly called containers or collections because a single tuple can contain or collect an arbitrary number of other objects.

Note: In Python, tuples support several operations that are common to other sequence types, such as lists, strings , and ranges . These operations are known as common sequence operations . Throughout this tutorial, you’ll learn about several operations that fall into this category.

In Python, tuples are ordered, which means that they keep their elements in the original insertion order:

The items in this tuple are objects of different data types representing a record of data from a database table. If you access the tuple object, then you’ll see that the data items keep the same original insertion order. This order remains unchanged during the tuple’s lifetime.

You can access individual objects in a tuple by position, or index. These indices start from zero:

Positions are numbered from zero to the length of the tuple minus one. The element at index 0 is the first element in the tuple, the element at index 1 is the second, and so on.

Cool! You’ve had a first glance at tuples. It’s time to dive deeper into all of the above characteristics of tuples and more. To kick things off, you’ll start by learning the different ways to create tuples in Python.

Constructing Tuples in Python

A tuple is a sequence of comma-separated objects. To store objects in a tuple, you need to create the tuple object with all its content at one time. You’ll have a couple of ways to create tuples in Python. For example, you can create tuples using one of the following alternatives:

  • Tuple literals
  • The tuple() constructor

In the following sections, you’ll learn how to use the tools listed above to create new tuples in your code. You’ll start off with tuple literals.

Tuple literals are probably the most common way to create tuples in Python. These literals are fairly straightforward. They consist of a comma-separated series of objects.

Here’s the general syntax of a tuple literal:

This syntax creates a tuple of n items by listing the items in a comma-separated sequence. Note that you don’t have to declare the items’ type or the tuple’s size beforehand. Python takes care of this for you.

In most situations, you’ll create tuples as a series of comma-separated values surrounded by a pair of parentheses:

The pair of parentheses in this construct isn’t required. However, in most cases, the parentheses improve your code’s readability. So, using the parentheses is a best practice that you’ll see in many codebases out there. In contrast, the commas are required in the tuple literal syntax.

Here are a few examples of creating tuples through literals:

In the first three examples, you create tuples of heterogeneous objects that include strings, numbers , and Boolean values. Note that in these examples, each tuple represents a single object with different elements. So, the name of the underlying tuple is a singular noun.

In the final example, you create a tuple of homogeneous objects. All the items are strings representing the weekdays. The name of the tuple is a plural noun.

In the case of days , you should note that Python ignores any extra comma at the end of a tuple, as it happens after "Sunday" . So, it’s optional but common practice because it allows you to quickly add a new item if needed. It’s also the default format that code formatters like Black apply to multiline tuples.

Note: In all of the above examples, the tuples have a fixed number of items. Those items are mostly constant in time, which means that you don’t have to change or update them during your code’s execution. This idea of a fixed and unchangeable series of values is the key to deciding when to use a tuple in your code.

Even though the parentheses aren’t necessary to define most tuples, you do have to include them when creating an empty tuple:

Note that once you’ve created an empty tuple, you can’t populate it with new data as you can do with lists. Remember that tuples are immutable. So, why would you need empty tuples?

For example, say that you have a function that builds and returns a tuple. In some situations, the function doesn’t produce items for the resulting tuple. In this case, you can return the empty tuple to keep your function consistent regarding its return type.

You’ll find a couple of other situations where using the parentheses is required. For example, you need it when you’re interpolating values in a string using the % operator :

In the first example, you use a tuple wrapped in parentheses as the right-hand operand to the % operator. In this case, the interpolation works as expected. In the second example, you don’t wrap the tuple in parentheses, and you get an error.

Another distinctive feature of tuple literals appears when you need to create a single-item tuple. Remember that the comma is the only required part of the syntax. So, how would you define a tuple with a single item? Here’s the answer:

To create a tuple with a single item, you need to place the item followed by a comma. In this example, you define two tuples using this pattern. Again, the parentheses aren’t required. However, the trailing comma is required.

Single-item tuples are quite useful. For example, if you have a class that generates a large number of instances, then a recommended practice would be to use the .__slots__ special attribute in order to save memory. You’ll typically use a tuple as the value of this attribute. If your class has only one instance attribute , then you’ll define .__slots__ as a single-item tuple.

You can also use the tuple() class constructor to create tuple objects from an iterable , such as a list, set , dictionary, or string. If you call the constructor without arguments, then it’ll build an empty tuple.

Here’s the general syntax:

To create a tuple, you need to call tuple() as you’d call any class constructor or function . Note that the square brackets around iterable mean that the argument is optional , so the brackets aren’t part of the syntax.

Here are a few examples of how to use the tuple() constructor:

In these examples, you create different tuples using the tuple() constructor, which accepts any type of iterable object.

Note: The tuple constructor also accepts sets . However, remember that sets are unordered data structures. This characteristic will affect the final order of items in the resulting tuple.

Finally, note that calling tuple() without an argument returns a new empty tuple. This way of creating empty tuples is rare in practice. However, it can be more explicit and help you communicate your intent: creating an empty tuple . But in most cases, assigning an empty pair of parentheses to a variable is okay.

The tuple() constructor comes in handy when you need to create a tuple out of an iterator object. An iterator yields items on demand. So, you don’t have access to all of its data at one time. The tuple() constructor will consume the iterator, build a tuple from its data, and return it back to you.

Here’s an example of using the tuple() constructor to create a tuple out of a generator expression , which is a special kind of iterator:

In this example, you use tuple() to build a tuple of square values. The argument to tuple() is a generator expression that yields square values on demand. The tuple constructor consumes the generator and builds the tuple containing all the data.

Note: It’s important to note that to create a stand-alone generator expression, you do need an enclosing pair of parentheses. In the above example, the required parentheses are provided by the call to tuple() .

You could’ve also done something like tuple((x**2 for x in range(10))) , but this would be less readable and clean.

As a side note, you need to consider that potentially infinite iterators will hang your code if you feed them to the tuple() constructor.

You can extract the items of a tuple using their associated indices . What’s an index? Each item in a tuple has an integer index that specifies its position in the tuple. Indices start at 0 and go up to the number of items in the tuple minus 1 .

To access an item through its index, you can use the following syntax:

This construct is known as an indexing operation. The [index] part is the indexing operator , which consists of a pair of square brackets enclosing the target index. You can read this construct as from tuple_object give me the item at index .

Here’s how this syntax works in practice:

Indexing a tuple with different indices gives you direct access to the associated values. If you use Big O notation for time complexity , then you can say that indexing is an O(1) operation. This means that tuples are quite good for those situations where you need to quickly access specific items from a series.

Here’s a visual representation of how indices map to items in a tuple:

“Jane Doe” 25 1.75 “Canada”

In any Python tuple, the index of the first item is 0 , the index of the second item is 1 , and so on. The index of the last item is the number of items minus 1 . In this example, the tuple has four items, so the last item’s index is 4 - 1 = 3 .

The number of items in a tuple defines its length . You can learn this number by using the built-in len() function:

With a tuple as an argument, the len() function returns a value representing the number of items in the target tuple. This number is the tuple’s length.

It’s important to note that, if you use an index greater than or equal to the tuple’s length, then you get an IndexError exception:

In this example, you get an IndexError as a result. Using out-of-range indices might be a common issue when you’re starting to use tuples or other sequences in Python. So, keep in mind that indices are zero-based, so the last item in this example has an index of 3 .

You can also use negative indices while indexing tuples. This feature is common to all Python sequences, such as lists and strings. Negative indices give you access to the tuple items in backward order:

A negative index specifies an element’s position relative to the right end of the tuple and back to the beginning. Here’s a representation of how negative indices work:

You can access the last item in a tuple using the index -1 . Similarly, the index -2 identifies the item next to the last, and so forth.

As you can see, negative indices don’t start from 0 . That’s because 0 already points to the first item. This may be confusing when you’re first learning about negative and positive indices. Don’t worry, you’ll get used to this behavior.

If you use negative indices, then -len(tuple_object) will be the first item in the tuple. If you use an index lower than this value, then you’ll get an IndexError :

Using an index lower than -len(tuple_object) produces an error because the target index is out of range.

As you already know, tuples can contain items of any type, including other sequences. When you have a tuple that contains other sequences, you can access the items in any nested sequence by chaining indexing operations.

To illustrate, say that you have the following tuple:

Your employee tuple has an embedded tuple containing a series of skills. How can you access individual skills? You can use the following indexing syntax:

The numbers at the end of each index represent the different levels of nesting in the tuple. So, to access individual skills in the employee tuple, you first need to access the last item and then access the desired skill:

You can access items in the nested sequence by applying multiple indexing operations in a row. This syntax is extensible to other nested sequences like lists and strings. It’s even valid for dictionaries, in which case you’ll have to use keys instead of indices.

Like other Python sequences, tuples allow you to extract a portion or slice of their content with a slicing operation, which uses the following syntax:

The [start:stop:step] part of this construct is known as the slicing operator . It consists of a pair of square brackets and three optional indices: start , stop , and step . The second colon is optional too. You typically use it only in those cases where you need a step value different from 1 .

All the indices in the slicing operator are optional. Here’s summary of their meanings and default values:

Index Description Default Value
Specifies the index at which you want to start the slicing. The item at this index is included in the final slice.
Specifies the index at which you want the slicing to stop extracting items. The item at this index isn’t included in the final slice.
Provides an integer value representing how many items the slicing will jump through on each step. If is greater than , then jumped items won’t be in the resulting slice.

You can combine these indices in different ways to obtain specific portions of a given tuple. Here are a couple of examples of slicing variations:

In these examples, the first slicing allows you to extract the business days, while the second slicing gives you the weekend.

You can experiment with different combinations of indices and different tuples to get a grasp of how this construct works.

To dive deeper into slicing operations, check out the Retrieving Multiple Items From a List: Slicing section of Python’s list Data Type: A Deep Dive With Examples . For the most part, the same slicing operations that apply to lists are valid for tuples, except for those that mutate a list in place.

Speaking of mutations, immutability is a fundamental feature of tuples. This feature affects how you use tuples in practice. In the following section, you’ll learn how immutability impacts the behavior of tuples.

Python’s tuples are immutable , which means that once you’ve created a tuple, you can’t change or update its items in place . This characteristic of tuples implies that you can’t use indices to update individual items in an existing tuple:

Because tuples are immutable, if you try to change the value of a tuple item through an assignment , then you get a TypeError telling you that tuples don’t support item assignments. So, once you’ve created a tuple, there’s no way to update its content. You can only create a new tuple object with the new or updated content.

Another implication of tuples being immutable is that you can’t grow or shrink an existing tuple. Unlike lists, tuples don’t have .append() , .extend() , .insert() , .remove() , and .clear() methods.

Additionally, tuples don’t support the del statement on items:

You can’t delete tuple items using the del statement. If you try to do it, then you get a TypeError telling you that tuples don’t support item deletion, as you can confirm in the example above.

Even though Python tuples are immutable, there’s a subtle detail that you need to keep in mind when working with tuples in your code. Tuples can store any type of object, including mutable ones. This means that you can store lists, sets, dictionaries, and other mutable objects in a tuple:

This tuple stores information about a student. The first two items are immutable. The third item is a list of subjects. Python’s lists are mutable, and therefore, you can change their items in place. This is possible even if your target list is nested in an immutable data type like tuple .

To change or update the list of subjects in your student_info tuple, you can use chained indices as in the following example:

As you can conclude from this example, you can change the content of mutable objects even if they’re nested in a tuple. This behavior of tuples may have further implications. For example, because tuples are immutable, you can use them as keys in a dictionary:

In this code, you use tuples as keys for the student_courses dictionary. The example works as expected. However, what will happen if the tuples that you want to use as keys contain mutable objects? Consider the following variation of the previous example:

In summary, you can use tuples as keys in a dictionary only if all their items are of hashable types. Otherwise, you’ll get an error.

Python has the notion of packing and unpacking tuples. For example, when you write an assignment statement like point = x, y, z , you’re packing the values of x , y , and z in point . That’s how you create new tuple objects.

You can also do the inverse operation and unpack the values of a tuple into an appropriate number of variables. To continue with the point example, consider the following code:

The highlighted line does the magic of unpacking the content of point into three variables. Note that the values go to the variables in order. The first value goes to the first variable, the second value goes to the second variable, and so on.

Note: Python 3.5 extended the tuple unpacking syntax to work with all kinds of iterables. So, nowadays, you can say iterable unpacking instead of just tuple unpacking.

In regular unpacking, the number of variables must match the number of values to unpack. Otherwise, you get an error:

In this case, you’re trying to unpack a three-item tuple into two variables. You get an error because Python doesn’t know how to unambiguously perform the unpacking.

The unpacking syntax works like a charm and has several common use cases. One of the most popular use cases is to take advantage of unpacking for swapping values between variables. For example, to swap values between two variables with regular assignments, you have to use a temporary variable:

If you have to do this operation often in your code, then this approach can become cumbersome. Fortunately, the unpacking syntax can help you do the swapping in a quick, elegant way:

In the highlighted line, the left-hand operand provides the variables, while the right-hand operand provides the values to unpack. This expression allows you to quickly swap values between variables without an intermediate step.

Parallel assignment is another cool use case of tuple unpacking. For example, say that you often do something like the following:

In this example, you use independent assignment to grab values from the employee tuple. Even though this code works, the index handling can be error-prone and confusing. Here’s a Pythonic solution using tuple unpacking:

With tuple unpacking, you solve the problem in a single line without using indices. This Pythonic approach will make your code easier to read and understand. It’ll also make the code less error-prone.

Python also has a packing and unpacking operator ( * ) that you can use to make your unpacking statements more flexible. For example, you can use this operator to collect multiple values in a single variable when the number of variables on the left doesn’t match the number of items in the tuple on the right:

In these examples, the original tuple has five items. In the first unpacking, you use the unpacking operator to collect four items in head and one item in last . Note that the * operator collects the values in a new list object rather than in a tuple.

In the second and third examples, you collect several values from the middle and tail of numbers using the packing operator ( * ).

The final example shows how you can grab the first value from a tuple and pack the rest of the values in a disposable variable. This construct can be useful when you only need the first value. However, it may be confusing to others. Doing something like first = number[0] would probably be more intuitive and natural.

Another interesting use case of the packing and unpacking operator is when you need to merge a few tuples together to build a new one:

In the highlighted line, you use the * operator to unpack the content of name and contact , merging them to create a new tuple with all the data from both. This syntax provides a quick way to merge tuples in your code.

In some situations, you’ll need to return multiple values from a function or method . To do that, you can build a return statement with a comma-separated series of arguments. Yes, that’s a tuple. As a result, whenever you call the function, you’ll get a tuple of values.

Note: You can also return multiple values from a function using a list, in which case you need to explicitly use square brackets to wrap the values or build the list beforehand. This approach is useful when you need to continue mutating the data after receiving it from the function. If you don’t need to mutate the resulting data, then using a tuple is the way to go.

The built-in divmod() function is a good example of a function that returns multiple values. This function takes two numbers and returns a tuple containing the quotient and the remainder when doing integer division:

This function returns two values as a tuple. Because the function returns a tuple, you can use the unpacking syntax to store each value in its dedicated variable. You can use this pattern in your custom functions too.

For example, say that you want to write a function that returns the minimum and maximum value from an input iterable:

In this function, you first create a tuple from the input iterable. This step guarantees that the data container supports the built-in len() function. With the conditional statement, you check if the input iterable is empty, in which case you raise an exception .

If the input iterable contains at least one value, then you use the built-in min() and max() functions to determine the minimum and maximum values in the input data.

Finally, you return both values from the function. Again, when you separate a series of values with commas, you create a tuple. So, this function returns a tuple object.

Note: If your functions needs several different return types, then you’re dealing with a more complex scenario. In this case, you can get some help from How to Use Type Hints for Multiple Return Types in Python .

You’ll note that returning multiple values as a tuple is one of those use cases where the parentheses don’t add much to the readability of your code. So, most Python developers don’t use them here.

You typically make copies of an object when you need to transform the data while preserving the original data unchanged. Copies are quite useful when you’re working with mutable data types, such as lists and dictionaries. They allow you to make changes in the copy without affecting the original data.

Because tuples are immutable data types, there’s no way to mutate their items in place. So, creating copies of an existing tuple isn’t really necessary. The usual shallow copying techniques that you use with lists, such as the slicing operator or the copy.copy() function, create aliases instead of copies:

Both student_info and student_profile hold references to the same tuple object. You can confirm this fact by using the built-in id() function, which takes an object as an argument and returns its identity. So, student_profile is an alias of student_info rather than a copy. Also, note how items at the same index position in both aliases share the same identity.

Note: In Python, an object’s identity is a unique identifier that distinguishes it from other objects. You can use the built-in id() function to get the identity of any Python object. In Python’s CPython implementation , an object’s identity coincides with the memory address where the object is stored.

The copy() function from the copy module produces an equivalent result:

Again, both variables hold references to the same tuple object and the same items. So, the copy() function doesn’t make any difference.

Wait, the tuple in the above example hosts a list object, which is mutable. What would happen if you changed one of its items? Would the change affect both student_profile and student_info ? Run the code below to answer these questions:

In this example, you change the "History" subject to "Computer science" in student_profile . The change also affects the original data in student_info .

Maybe you’ve made deep copies of lists using the deepcopy() function from the copy module, and you’re wondering if you can do the same with tuples. In this case, you’re looking for a new tuple that contains copies of the contained elements. Does that work with tuples? Take a look at the following example:

In this example, you use deepcopy() to create a copy of your original tuple, student_info . Note that both variables now point to different tuple objects with different identities. However, the items at the same index in both tuples hold references to the same objects.

Now go ahead and change the subject again:

This time, changes to the mutable object in student_profile don’t affect the original data in student_info .

In summary, shallow copies of tuples don’t create copies but aliases. Deep copies create new tuple objects with references to the same items. If the deep-copied tuple contains mutable objects, then Python creates a new copy of these objects so that mutations to them in the copy won’t affect the original data.

Concatenating and Repeating Tuples

Like lists and strings, tuples also support concatenation and repetition. You can use the plus operator ( + ) to concatenate tuples together and the star operator ( * ) to repeat the content of an existing tuple.

In the following sections, you’ll learn how these two operations work on Python tuples and how to use them in your code.

Concatenation consists of joining two things together. To concatenate two tuples in Python, you can use the plus operator ( + ). In this context, this operator is known as the concatenation operator .

Here’s how it works:

In this example, you combine two tuples containing personal and professional information to build an employee’s profile. Note that the concatenation operator creates a new tuple object every time.

Note: You can only concatenate a tuple with another tuple. If you try to concatenate a tuple with a list, then you’ll get an exception:

Python’s concatenation operator raises a TypeError exception when you try to concatenate a tuple with a different sequence data type, such as a list.

The concatenation operator has an augmented variation , which uses the += operator. Here’s how this operator works:

The augmented concatenation operator works on an existing tuple, like profile in this example. It takes a second tuple and creates a new one containing all the items from the two original tuples. The augmented concatenation operator is a shortcut to an assignment like x = x + y , where x and y are tuples.

Because tuples are immutable, the augmented concatenation operator creates a new tuple every time. That’s why the identity of profile changes after running the concatenation.

Repetition is all about cloning the content of a given container a specific number of times. Tuples support this feature with the repetition operator ( * ), which takes two operands:

  • The tuple whose content you want to repeat
  • The number of times that you need to repeat the content

To illustrate how repetition works with tuples, consider the following example:

Here, you first repeat the content of numbers three times and get a new tuple as a result. Then you repeat the content of numbers four times. Note that the order of the operands doesn’t affect the repetition result.

The repetition operator also has an augmented variation that you’ll call the augmented repetition operator. This variation is represented by the *= operator. Here’s how it works:

In the highlighted line, the *= operator takes the current content of numbers , repeats it three times, and assigns it back to the numbers variable. Note that this operator always creates a new tuple object because tuples are immutable. You can confirm this fact by checking the identity of numbers before and after the repetition.

Reversing and Sorting Tuples

In Python, you’ll have the built-in reversed() and sorted() functions that you can use when you need to reverse and sort tuples. You can also create reversed tuples using the slicing operator with a step of -1 . In the following sections, you’ll learn how to reverse and sort tuples using these tools.

The built-in reversed() function takes a sequence as an argument and returns an iterator that yields the values from the input sequence in reverse order. Tuples support this function:

When you call reversed() with a tuple as an argument, you get an iterator object that yields items in reverse order. So, in this example, you create a reversed tuple out of the days of the week. Because reversed() returns an iterator, you need to use the tuple() constructor to consume the iterator and create a new tuple out of it.

You can also create a new reversed tuple by slicing an existing one with a step of -1 . The following code shows how to do it:

The [::-1] variation of the slicing operator does the magic in this code example. It creates a copy of the original tuple with the items in reverse order. But how does it work?

When the third index ( step ) in a slicing operation is a positive number, the slicing extracts the items from left to right. In contrast, when step is a negative number, such as -1 , the slicing extracts the items from right to left. That’s why this variation of the slicing operator allows you to get a reversed copy of an existing tuple.

Sorting a tuple may be a requirement in your code. In this case, you can use the built-in sorted() function, which takes an iterable of values as an argument and returns a list of sorted values:

When you pass a tuple to sorted() , you get a list of sorted values as a result. In this example, you use a tuple of numbers and sort them using sorted() .

Note: It’s important to recognize that sorted() returns a list rather than an iterator. This behavior differs from reversed() , which returns an iterator instead of a list.

When it comes to sorting tuples, you need to consider that they typically contain heterogeneous data, in which case sorting may not make sense. A typical example of a tuple use case is a database record. In this scenario, you can find strings, numbers, dates, and many other data types.

When you’re working with tuples containing heterogeneous data, then using sorted() won’t be an option:

In this example, sorted() raises an exception because it can’t compare strings and integer numbers using the less than operator ( < ).

By default, the sorted() function sorts items in ascending order. If you need to sort the items in descending order, then you can use the reverse keyword-only argument . If you set reverse to True , then you get the data in descending order:

When you set the reverse argument to True , you tell sorted() to return a list of items sorted in reverse order.

The sorted() function accepts another keyword-only argument called key . This argument allows you to specify a one-argument function that sorted() will use to extract a comparison key from each item in the input iterable.

The key argument is quite useful in those situations where the tuple that you need to sort holds other container types, such as other tuples. The example below shows how to sort a tuple of tuples by the second item of each nested tuple:

In this example, you have a tuple containing two-item tuples. The first item is the name of a fruit, and the second item is the corresponding price. You sort the nested tuples by price. To do this, you use a lambda function as the key argument to sorted() . This lambda takes a fruit as an argument and returns its price, which is the value at index 1 .

In practice, the key argument to sorted() is quite useful because it allows you to fine-tune the sorting process by changing the sorting criteria according to your specific needs.

Traversing Tuples in Python

Sometimes, you’ll need to loop over each value in a tuple. Python provides a few tools that allow you to do this. The most popular are for loops, comprehensions , and generator expressions. However, you can also use some of Python’s functional programming tools that implement an implicit loop, such as the map() and filter() functions.

In the following sections, you’ll learn how to traverse tuples using these tools. To kick things off, you’ll start with for loops.

To illustrate how to iterate over a tuple using a Python for loop, say that you have a tuple of tuples. Each nested tuple contains a month of the year and the income of a company during that month. Now say that you want to know the year’s income. You can do something like the following:

To use a for loop with a tuple, you just have to provide a suitable loop variable and then place the tuple after the in keyword. In this example, you loop over monthly_incomes . Inside the loop, you use the accumulator variable, total_incomes , to compute the year’s income using the augmented addition operator.

You can also use tuple unpacking in the header of a for loop. For example, say that you want to create a short report that computes the income per quarter. In this case, you can do something like this:

Wow! There’s a lot happening in the loop’s header. It goes over the items in monthly_incomes . The built-in enumerate() function allows you to enumerate your months starting from 1 up to 12 . In this example, enumerate() yields nested tuples of the form (index, (month, income)) . That’s why the loop variables reflect this pattern.

Note: For a deep dive into using the built-in enumerate() function, check out Python enumerate() : Simplify Loops That Need Counters .

Then, you compute the quarter’s income using the accumulator variable, quarter_income . If the current index is divisible by 3 , then you print the quarter’s income and reset the accumulator to start the computation for the next new quarter. The code’s output shows a report with information about each month and the summary of every quarter. Isn’t that cool?

Comprehensions and generator expressions provide another quick way to iterate through your tuples. For example, say that you have a tuple of numbers as strings and need to create a new tuple of numbers out of your original data.

In this situation, you can use a list comprehension to iterate over the tuple while converting each string to a number. Then you can use the tuple() constructor to get your new tuple:

In this example, the comprehension goes through numbers and converts every string into an integer number using int() . Then, you use the resulting list directly as an argument to the tuple() constructor, which gives you a new tuple object.

You can also make this example more efficient and concise by using a generator expression instead of a comprehension. To do that, you only need to remove the square brackets that delimit the comprehension:

This updated version of your code looks cleaner, and it’s more efficient regarding memory consumption. You turned the comprehension into a generator expression that yields converted values on demand. The tuple() constructor consumes the iterator and builds a new tuple out of the resulting data.

Exploring Other Features of Tuples

Python’s tuple is a pretty lightweight data type with limited functionality. Tuples are immutable, so they don’t need methods to add, update, or remove items. In consequence, they have only two methods as part of their public API : .count() and .index() .

With .count() , you can count the number of occurrences of a given item in a tuple. The method allows you to check how many times a given item is present in the target tuple:

The .count() method takes a potential item as an argument, traverses the underlying tuple, and finds out how many times the target item is present. If the item isn’t present in the tuple, then .count() returns 0 .

Because most tuple use cases imply storing items of different types, such as those in a record of a database, the .count() method may have limited practical applications. You’ll probably find .count() more useful when you’re working with list objects, where the items are often of the same type and represent homogeneous and related values.

On the other hand, the .index() method allows you to locate the first occurrence of an item in an existing tuple. If the target item is in the tuple, then the method returns its index. Otherwise, the tuple raises a ValueError exception:

In the first call to .index() , you get the index of the first occurrence of "apple" in the underlying tuple. In the second call, because "mango" isn’t present in fruits , you get a ValueError with a self-explanatory message.

If you need to quickly determine whether a value is present in a tuple, then you can use the in or not in operators, which will run a membership test on your target tuple.

Note: To learn more about the in and not in operators and how to perform membership tests, check out Python’s “in” and “not in” Operators: Check for Membership . These operators can also be useful when you need to check if a Python string contains a substring .

As its name suggests, a membership test allows you to determine whether an object is a member of a collection of values. The general syntax for membership tests on a tuple looks something like this:

The first expression allows you to determine whether item is in tuple_object . The second expression works in the opposite way, allowing you to check if item is not in list_object .

Here’s how membership tests work in practice:

In this example, you have a tuple of skills, and you use in and not in to determine whether a given skill is in the tuple. If the target skill is present in the underlying tuple, then you get True with in and False with not in . In contrast, if the target skill isn’t in the tuple, then you get False with in and True with not in .

For tuples and lists, the membership operators use a search algorithm that iterates over the items in the underlying collection. Therefore, as your iterable gets longer, the search time increases in direct proportion. Using Big O notation , you’d say that membership operations on tuples have a time complexity of O(n) .

If your code runs a lot of membership tests on tuples, then you may consider opting for sets if possible. Python implements sets as hash tables , so lookup operations on sets have a time complexity of O(1) , which makes them more efficient than tuples and lists in the context of membership tests.

While working with tuples, you may need to know the number of items in a given tuple. This number is commonly known as the tuple’s length and can be pretty useful. To determine the length of a tuple, you can use the built-in len() function:

In this example, you use len() to determine the number of items in a tuple. Internally, tuples keep track of their length, so calling len() with a tuple as an argument is a fast operation with a time complexity of O(1) .

You may need to compare tuples at some point in your coding journey. Fortunately, tuples support the standard comparison operators .

When you compare two tuples, Python uses lexicographical ordering . It compares the first two items of each involved tuple. If they’re different, then this difference determines the comparison result. If they’re equal, then Python compares the next two items, and so on, until either tuple is exhausted.

Here are some examples that compare tuples of integer values:

In these examples, you compare tuples of numbers using the standard comparison operators. Python runs an item-by-item comparison. So, for example, in the first expression above, Python compares the 2 in the left tuple and the 2 in the right one. They’re equal, and Python continues by comparing 3 and 3 to conclude that both tuples are equal.

In the second expression, Python compares 5 and 7 . They’re different. Because 5 is less than 7 , this individual comparison determines the result of the entire expression, and you get True as a result.

In the third expression, both tuples contain the same values. Because equality is included in the comparison, you get True as a result.

You can also compare tuples of different lengths:

In the first expression, you get True because 5 is less than 8 . This comparison determines the final result.

In the second example, Python compares 5 and 5 . They’re equal. So, Python tries to continue the comparison. Because there are no more items in the right-hand tuple, Python concludes that the left-hand tuple is greater and, therefore, the comparison is False .

In the process of comparing sequences, Python applies specific rules depending on the type of the compared items. This behavior is pretty relevant for tuples because they typically hold heterogeneous objects.

Consider the following example:

The tuples in the first comparison contain the same data. The values are a string, an integer, a floating-point number, and a tuple. When comparing item by item, Python uses its internal rules for comparing strings, integers, floating-point numbers, and tuples, respectively.

Note that in the second example, the second element in the right-hand tuple is a string rather than a number. Numbers and strings aren’t equal, so the comparison is false. This comparison only works because of the equality operator.

If you use most other comparison operators, such as < or > , then the comparison raises a TypeError exception, as you can conclude from the final example.

If you’re new to Python and are just starting out with tuples, then you should know about a couple of gotchas that can cause subtle issues in your code. Arguably, the most common gotcha with tuples is to forget the trailing comma when defining one-item tuples:

In this example, you attempt to create a one-item tuple using a pair of parentheses. Later in the code, when you call the .index() method, you get an error telling you that integer objects don’t have this method.

What just happened? When you define a tuple, the parentheses are superfluous. They help you enhance readability but nothing else. The commas are what really defines a tuple. To create a one-item tuple, you need to include a trailing comma after the item:

The trailing comma after 42 creates the actual tuple. Now the code works correctly, and you can call .index() as needed.

Another gotcha that can bite you when you’re working with tuples is hashability , which is the possibility of using a hash function to calculate a unique hash code out of a given value or data structure. In Python, it’s common to hear people say that because tuples are immutable, you can use them as keys in a dictionary.

However, this assumption isn’t always true. When you store mutable objects in a tuple, that tuple won’t be hashable and won’t work as a dictionary key. You already saw an example of this issue in the Exploring Tuple Immutability section.

Here’s another example. This time, you create a dictionary of cities. The keys include the city name and its geographical coordinates. The values hold the population of each city:

In this example, you use tuples as the keys of your cities dictionary. Tuples are immutable, but this fact doesn’t guarantee that all tuples can work as dictionary keys. In this specific case, your tuples contain lists, which are mutable. Therefore, your code fails with a TypeError exception.

Using Alternatives to the Built-in tuple Type

Up to this point, you’ve learned a lot about Python tuples. You now know that they’re immutable sequences that can contain heterogeneous data. Even though tuples have a few cool features, their functionality is pretty limited.

For example, you can only access tuple items using numeric indices. This can be error-prone and annoying because it forces you to remember the right index every time.

In this example, you have a tuple that contains information about a person. Later in your code, you access the first item, which is the person’s name. However, the index to access the person’s age in the last expression is wrong, and the age variable ends up holding the incorrect data.

Fortunately, Python has other classes that can emulate a tuple but offer a more readable and explicit interface that doesn’t rely on numeric indices. In the following sections, you’ll learn the basics of these classes. To kick things off, you’ll start with traditional named tuples .

A named tuple is a tuple subclass that incorporates named fields into its public interface. These named fields allow you to access the items in the underlying tuple using dot notation and the appropriate field name, which is more readable and explicit than using an index.

Note: To learn more about name tuples in Python, check out: Write Pythonic and Clean Code With namedtuple .

To illustrate how this idea of named fields works, say that you want to store the person data from the previous section in an immutable sequence—like a tuple—that allows you to access its items using descriptive names. For example, you’d like to do something like person.name to access the name instead of doing person[0] , which is much less readable and explicit.

In that situation, you can use the namedtuple() factory function from the collections module:

In this code snippet, you first import the namedtuple() factory function. Next up, you create the Person class by calling the function with two arguments. The first argument is the class name, while the second argument is a string that provides the field names separated by whitespaces. In this specific example, your tuple-like class will have three fields: name, age, and position.

Here’s how you can use this tuple-like class in your code:

In this example, you instantiate Person using concrete values for all three fields. Note how you can access each field by using dot notation and the field name. Because Person is a subclass of tuple , you can also access its items by index, as you’d do with a regular tuple.

Another important aspect to take into account is that the instances of a named tuple are also immutable like their superclass, tuple :

There’s no way to change the content of a named tuple in place. Note that both assignments fail. If you use dot notation for attribute assignment, then you get an AttributeError because the fields are immutable. If you try to use an index assignment, then you get a TyperError exception.

A cool use case of named tuples is to return multiple values from a function. Consider the following function, which wraps the return value of divmod() in a named tuple:

Your function returns a tuple of values just like the original divmod() function does. However, the returned tuple object is more readable and allows you to quickly identify the meaning of each value in the result.

Python 3.5 introduced a module called typing to support type hints . This module exports the NamedTuple class, which is a typed version of namedtuple . With NamedTuple , you can create tuple subclasses with type hints and default values.

To illustrate how NamedTuple can be helpful, say that you have the following CSV file containing data from your company’s employees:

You want to load the content of this file and extract every record or line to a tuple-like object. In this situation, you can do something like the following:

In this code snippet, you import the NamedTuple class from the typing module. This class will allow you to create the employee records.

Then you define a NamedTuple subclass called Employee to hold the data of every employee. Note that in this class, you provide the named fields as class attributes with their corresponding type hint. In the case of the position field, you also provide a default value, "Python Developer" . This default can be handy in many situations.

Now you’re ready to load the data from your CSV file:

In this code, you first import the csv module to manipulate the CSV file. In the with statement , you open employees.csv for reading. Then, you use reader() to load the file content. The call to the built-in next() function skips the file’s first line, which contains the headers.

The for loop iterates over the rest of the rows in the CSV file and appends them to a list of employees. To create a record for each employee, you use the Employee class with the data for each field as arguments. Note how you use the built-in int() function to convert the age to an integer value and make it type-consistent.

That’s it! Now you have a list of employee records from your original data in the CSV file. You can use this list in your code:

This way, you keep your employees’ data in an immutable tuple-like object that has the additional benefit of providing named fields to access the data in an explicit and readable manner.

Python 3.7 added data classes to the standard library. According to PEP 557 , they’re similar to named tuples but mutable by default. You can use data classes to replace your named tuples with a more powerful tool that has many additional features, including the possibility of having type hints, default attribute values, methods , and more. They also have the capability of becoming immutable.

Note: To learn more about data classes and what you can do with them, check out Data Classes in Python 3.7+ (Guide) .

You can use the @dataclass decorator from dataclasses to create a data class. Here’s a data class–based version of your Employee class:

This class is quite similar to the NamedTuple version. Instead of inheriting from another class, you use the @dataclass decorator, which you need to import from the dataclasses module. The rest of the code is the same.

Additionally, this new version of Employee works the same as its old version based on NamedTuple :

Note that you’ve used the same code to process the data class–based version of your Employee class.

However, there’s a detail that you must keep in mind. Now your records are mutable by default, which means that you can update an employee’s data:

In this example, you update Joe’s name by assigning a new value to its .name attribute. If you’d like to avoid this behavior, then you can pass the frozen argument to the @dataclass decorator on the definition of Employee :

Setting frozen to True makes your data class immutable. From this point on, you won’t be able to modify its data fields. To confirm this, run the code to build the employees list again and try to update Joe’s name:

Now, when you try to modify the value of one of the instance attributes of your Employee class, you get a FrozenInstanceError error. This is equivalent to an immutable data type like a tuple.

As you’ve learned throughout this tutorial, tuples are quite basic immutable sequences with a reduced set of features. However, they’re suitable for those use cases where you need to store heterogeneous data in a sequence that doesn’t change at all or doesn’t change frequently.

Database records are a good example of a typical use case of tuples. In this scenario, a tuple will provide a good representation of records or rows, where you have many fields containing heterogeneous values that shouldn’t change frequently.

In contrast, a list will be the right data type to represent database fields or columns because lists typically store homogeneous data that can change frequently. This will allow you to add or remove rows in your database and to update their content.

In general, you should use tuples when you need to:

  • Ensure data integrity : Tuples are immutable, meaning that you can’t modify their elements after creation. This immutability guarantees data stability, ensuring that the values in the tuple remain unchanged.
  • Reduce memory consumption : Tuples have less memory overhead compared to lists since they allocate a fixed amount of memory. This is particularly advantageous when working with large collections of data or in memory-constrained environments.
  • Improve performance : Tuples are generally more efficient than lists in terms of creation, iteration, and element access. This can result in improved performance, especially when working with large datasets.

If you’re in one of these scenarios, then favor using tuples over other similar sequences like lists, for example.

Some more concrete use cases of tuples include the following:

  • Associating two or more values (pairs, trios, and so on)
  • Representing database records
  • Providing multi-value keys in dictionaries

Here are a few quick examples of these use cases:

The first tuple represents a color using the RGB color model. This is an example of related values that you group together in a trio that may remain unchanged over time. The second tuple holds a car’s information, which you may have retrieved from a database.

Finally, the capital_cities dictionary has tuples as keys. Each key contains the capital city of a given country and the corresponding geographical coordinates.

You’ve delved into the core features and functionalities of Python’s tuples. You now know that tuples are immutable sequences that provide a reliable container for data that’s likely to remain unmodified during your code’s lifetime.

You’ve also learned about various aspects of tuple usage, including their most common use cases. Tuples are a great tool for any Python developer, and you’ll find them in most codebases out there.

In this tutorial, you’ve learned how to:

  • Create tuples using different approaches in Python
  • Access one or more items in a tuple using indexing and slicing
  • Reverse , sort , and traverse tuples using loops and other tools

With all this knowledge, you’re ready to write better code, as tuples offer an efficient and reliable way to handle and manipulate grouped data. Exploring tuples further and playing with them in various ways will take your Python powers to the next level.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate python

Related Tutorials:

  • Dictionaries in Python
  • Sets in Python
  • Python's list Data Type: A Deep Dive With Examples
  • Primer on Python Decorators
  • Python's Built-in Functions: A Complete Exploration

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python's tuple Data Type: A Deep Dive With Examples (Sample Code)

🔒 No spam. We take your privacy seriously.

python tuple does not support assignment

Clarifying NamedTuple inheritance in the typing spec

There are a few things re: NamedTuple inheritance in the typing spec that I’m hoping to clarify here. If we agree that the wording needs to be tweaked, I can submit a PR with the changes.

https://typing.readthedocs.io/en/latest/spec/namedtuples.html

The spec contains these two lines:

NamedTuple does not support multiple inheritance.
In Python 3.11 and newer, the class syntax supports generic named tuple classes.

The type error that gets thrown at runtime for named tuple multiple inheritance is:

This error does not appear when a class extends another named tuple class, it seems like it only appears when a class directly has NamedTuple in its base class list.

It also doesn’t specify what happens when a class inherits from two named tuple classes, like so:

The error message also implies that a generic named tuple definition of using the old style is also valid, like so:

Seems like the spec could be more explicit about what’s allowed and what’s not allowed. Thoughts?

Possibly the spec should actually say less about these details rather than more. The role of the typing spec is to describe the typing features that type checkers are supposed to support (and what the behaviour of type checkers should be regarding those features). It’s not really the purpose of the typing spec to exhaustively describe how parts of the typing module work at runtime. That information is more suited to the typing -module API reference in the CPython docs, and possibly HOWTO guides in Type System Guides — typing documentation .

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

'tuple' object does not support item assignment - open(index)

I am new in Python and I'm having some difficulties. I am trying this code:

I am getting this error:

TypeError: 'tuple' object does not support item assignment

I am sorry if my question is not smart enough, but I am used to code in C#. If someone can give me an advise how to fix this I will be greatfull. Thanks in advance.

Jonas's user avatar

  • Tuples are immutable. Here FullFilesList is a tuple.So when you try to assign a value at index it will rise TypeError . If you really want to do that convert FullFilesList to a list first, then mutate it and convert back to tuple again. –  user459872 Commented May 31, 2018 at 7:06

3 Answers 3

Even if FullFilesList was a list as its name implies, you're handling it in an unsupported manner. As a rule of thumb, don't index. Assigning indices that don't exist is an IndexError for a list, but an insertion for a dictionary. For tuples it's simply impossible. Either use append :

Or build the whole list in one step with a comprehension:

This tends to be easier to reason about, as there are no intermediate states of the list and we don't need to track its length (use len(FullFilesList) if you need that).

Yann Vernier's user avatar

When you declare FullFilesList = () , you're declaring a tuple (try typing type(FullFilesList) to verify). Tuples are immutable in Python, so you can't change FullFilesList in your for loop (you can only create a new tuple and make FullFilesList refer to that new tuple). See other posts such as this one: TypeError: 'tuple' object does not support item assignment when swapping values for more details.

When the Python interpreter runs the line FullFilesList=() , it creates a new empty tuple and binds the name FullFilesList to it. Tuples are immutable, they can't be changed after they're created, so you can't make much use of that variable. Instead, it sounds like you wanted a list. To create an empty list, use the same syntax you used when you created the list for ListB : FullFilesList=[]

You'll run into another issue though. When you want to add your values to FullFilesList , you're assigning them to an index that doesn't exist yet. That won't work. If you want to append each value to the end of the list, use the list.append method instead (again, like you did with ListB in your first loop).

There are also some minor things that could be improved in your code. Two I'll point out are naming conventions and with statements. Python convention for regular variable names is to use lowercase_names_with_underscores . Limit CapitalizedNames for classes, unless you're following an existing API that uses some other convention. You can read more about Python style suggestions in PEP 8 . Note that that's the style guide for the Python interpreter itself, not all Python projects follow it for their own code (but many do!).

My other suggestion has to do with making sure your files get closed after you're done with them. In your current code, you're often open ing a file, calling the readlines method on it and then dropping it without calling close on it. That will often work fine since the file object will be garbage collected and it will close as part of that process. But it's not guaranteed to work that way (the Python language does not make strong guarantees about when garbage collection will occur). A better approach is to ensure the file is closed yourself, using a with statement:

Blckknght's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Why did mire/bog skis fall out of use?
  • How to achieve 24t-38t front chainrings
  • What does St Paul mean by ' height or depth' in Romans 8:39?
  • "First et al.", many authors with same surname, and IEEE citations
  • Superuser and Sudo not working on Debian 12
  • Cheapest / Most efficient way for a human Wizard to not age?
  • Smallest prime q such that concatenation (p+q)"q is a prime
  • corresponding author not as the last author in physics or engineering
  • Calculate transition probabilities
  • Why believe in the existence of large cardinals rather than just their consistency?
  • Count squares in my pi approximation
  • Why did early pulps make use of “house names” where multiple authors wrote under the same pseudonym?
  • Would a material that could absorb 99.5% of light be able to protect someone from Night Vision?
  • What's "jam" mean in "The room reeled and he jammed his head down" (as well as the sentence itself)?
  • Parameters of the sampling distribution of the sample proportion
  • Can noun phrases have only one word?
  • Rav Moshe Feinstein's advice on doing teshuvah
  • Is it ok if I was wearing lip balm and my bow touched my lips by accident and then that part of the bow touched the wood on my viola?
  • Terminated employee will not help the company locate its truck
  • How can I prove that this expression defines the area of the quadrilateral?
  • Model looks dented but geometry is correct
  • My team is not responsive to group messages and other group initiatives. What should be the appropriate solution?
  • Flyback DCM Calculation
  • Is "Canada's nation's capital" a mistake?

python tuple does not support assignment

IMAGES

  1. Python TypeError: 'tuple' object does not support item assignment

    python tuple does not support assignment

  2. How to fix TypeError: 'tuple' object does not support item assignment

    python tuple does not support assignment

  3. Python TypeError: 'tuple' object does not support item assignment Solution

    python tuple does not support assignment

  4. Solve Python TypeError: 'tuple' object does not support item assignment

    python tuple does not support assignment

  5. Fix TypeError Tuple Does Not Support Item Assignment in Python

    python tuple does not support assignment

  6. TypeError: 'tuple' object does not support item assignment ( Solved )

    python tuple does not support assignment

VIDEO

  1. Python-v44-tuple-assignment

  2. tuple syntax doesn't have parens (beginner

  3. P40

  4. Unpacking a Tuple in Python

  5. TUPLES AND TUPLE ASSIGNMENT IN PYTHON / Explained in Tamil and English

  6. #5 Tuple in Python

COMMENTS

  1. TypeError: 'tuple' object does not support item assignment

    The values on the left and right-hand sides of the addition (+) operator have to all be tuples. The syntax for tuple slicing is my_tuple[start:stop:step]. The start index is inclusive and the stop index is exclusive (up to, but not including).. If the start index is omitted, it is considered to be 0, if the stop index is omitted, the slice goes to the end of the tuple.

  2. python

    How to fix 'Tuple' object does not support item assignment problem in Python 1 iterating over tuples inside a tuple and using string inside tuples as a variable

  3. 'tuple' object does not support item assignment

    However I get this error: TypeError: 'tuple' object does not support item assignment python; python-imaging-library; Share. Follow edited Mar 7, 2013 at 19:59. jleahy. 16.6k 6 6 gold ... Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list: [1,2,3] not (1,2,3)

  4. Solve Python TypeError: 'tuple' object does not support item assignment

    The Python TypeError: tuple object does not support item assignment issue occurs when you try to modify a tuple using the square brackets (i.e., []) and the assignment operator (i.e., =). A tuple is immutable, so you need a creative way to change, add, or remove its elements.

  5. Python typeerror: 'tuple' object does not support item assignment Solution

    typeerror: 'tuple' object does not support item assignment. While tuples and lists both store sequences of data, they have a few distinctions. Whereas you can change the values in a list, the values inside a tuple cannot be changed. Also, tuples are stored within parenthesis whereas lists are declared between square brackets.

  6. Tuple Object Does Not Support Item Assignment. Why?

    Does "Tuple Object Does Not Support Item Assignment" Apply to a List inside a Tuple? Let's see what happens when one of the elements of a tuple is a list. >>> values = (1, '2', [3]) If we try to update the second element of the tuple we get the expected error:

  7. How to Solve 'Tuple' Object Does Not Support Item Assignment (Python

    1 list1 = (1, 2, 3) ----> 2 list1[0] = 'one'. TypeError: 'tuple' object does not support item assignment. In this example, the name list1 refers to a tuple despite the list in the name. The name does not affect the type of variable. To fix this error, simply change the parentheses to square brackets in the constructor:

  8. How to Solve Python TypeError: 'tuple' object does not support item

    Tuples are immutable objects, which means you cannot change them once created. If you try to change a tuple in place using the indexing operator [], you will raise the TypeError: 'tuple' object does not support item assignment. To solve this error, you can convert the tuple to a list, perform an index assignment then…

  9. TypeError: 'tuple' object does not support item assignment: How to Fix

    TypeError: 'tuple' object does not support item assignment: How to Fix

  10. Fix TypeError Tuple Does Not Support Item Assignment in Python

    Did you assign a tuple to a new value and get the TypeError: tuple does not support item assignment in Python? If you're working with Python and you encounter the "TypeError: 'tuple' does not support item assignment" error, it means that you are trying to change the value of an element within a tuple, which is not possible.

  11. Tuple Error In Python

    Does the tuple object support item assignment? The answer to this question is a bit complicated. The tuple object does not support item assignment, meaning that you cannot reassign a value to a specific index within a tuple. However, you can replace an entire tuple with another tuple, as long as the new tuple has the same number of elements.

  12. Typeerror: 'tuple' object does not support item assignment

    What is Typeerror: 'tuple' object does not support item assignment? The "TypeError: 'tuple' object does not support item assignment" occurs when we attempt to change the value of an item in a tuple. To solve the error, convert the tuple to a list, change the item at the specific index, and convert the list back to a tuple.

  13. Python

    Python - 'tuple' object does not support item assignment. Ask Question Asked 11 years, 4 months ago. Modified 11 years, 4 months ago. ... TypeError: 'tuple' object does not support item assignment. 2. tuple as key to a dictionary says: 'tuple' object does not support item assignment. 3.

  14. TypeError 'tuple' object does not support item assignment

    To correct the Python TypeError: 'tuple' object does not support item assignment, you can do one of two things. You could either have mutable containers insi...

  15. Python Tuple

    Python is telling us that tuples do not support item assignment, which is a fancy way of saying you can't change their content once they're created. Advanced Tuple Techniques. Python tuples offer more than just a static collection of items. They can be used in more complex ways, such as tuple unpacking, nested tuples, and as dictionary keys.

  16. Python TypeError: 'tuple' object does not support item assignment Solution

    In Python, we have a built-in data structure " tuple " which is similar to a Python list and stores elements in sequential order.The only difference between a Python list and a tuple is that the tuple is an immutable data structure, which means once a tuple object is defined, we can not change its elements.

  17. Python's tuple Data Type: A Deep Dive With Examples

    Getting Started With Python's tuple Data Type. The built-in tuple data type is probably the most elementary sequence available in Python. Tuples are immutable and can store a fixed number of items. For example, you can use tuples to represent Cartesian coordinates (x, y), RGB colors (red, green, blue), records in a database table (name, age, job), and many other sequences of values.

  18. Writing over a tuple? : r/learnpython

    I can't reproduce that at all, I keep just getting a typical "Typewriter: 'tuple' object does not support item assignment'". I can't find any other mentions of this method online, the agreement across the board seems to be the only way to change a tuple is to convert it into a list.

  19. Python error: TypeError: 'tuple' object does not support item assignment

    Python - TypeError: 'tuple' object is not callable Hot Network Questions VBA: Efficiently Organise Data with Missing Values to Achieve Minimum Number of Tables

  20. Clarifying NamedTuple inheritance in the typing spec

    There are a few things re: NamedTuple inheritance in the typing spec that I'm hoping to clarify here. If we agree that the wording needs to be tweaked, I can submit a PR with the changes. https://typing.readthedocs.io/e…

  21. 'tuple' object does not support item assignment

    Tuples are immutable in Python, so you can't change FullFilesList in your for loop (you can only create a new tuple and make FullFilesList refer to that new tuple). See other posts such as this one: TypeError: 'tuple' object does not support item assignment when swapping values for more details.