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

typeerror 'tuple' object does not support item assignment in python

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.

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

typeerror 'tuple' object does not support item assignment in python

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 item assignment

5 minute read

Introduction

In Python, tuples are immutable, meaning that their elements cannot be modified once they have been assigned. This means that attempting to assign a value to an element in a tuple will result in the following error:

TypeError: ‘tuple’ object does not support item assignment

This error can be frustrating, but there are a few ways to work around it and achieve the desired outcome. In this article, we will explore three different ways to fix this error and give an in-depth explanation of how each method works.

Error and Cause

When attempting to reassign an item in a tuple using the indexing operator, such as:

Python will raise a TypeError, indicating that the tuple object does not support item assignment. This is because, as previously mentioned, tuples are immutable , and their elements cannot be modified once they have been assigned.

Python’s tuple is a built-in data structure that can store multiple values in a single object. This makes it useful for situations where you need to store multiple related values together.

Tuples are defined by enclosing the values in parentheses and separating them with commas. For example, the following code creates a tuple with three integers:

This tuple object, as stated before, is immutable, which means that once it is created, its elements cannot be modified. This means that you cannot add, remove, or change the values of the elements in a tuple.

This is why when you try to reassign a value to an element in the tuple using the indexing operator, such as my_tuple[0] = 4, python will raise a TypeError, indicating that the tuple object does not support item assignment.

Fix 1: Convert Tuple to List

One way to fix this error is to convert the tuple to a list, make the desired changes, and then convert it back to a tuple.

In the above example, we first convert the tuple to a list using the built-in list() function. Once the tuple is converted to a list, we can use the indexing operator to reassign the value at index 0 to 4.

Since lists are mutable, this operation is allowed. Once the desired changes have been made, we convert the list back to a tuple using the built-in tuple() function. The original tuple object is now replaced by the new tuple object which has the desired value at index 0.

It’s important to note that the original tuple remains unchanged, and the new tuple is created with the modified values. This method is useful when you want to make changes to the tuple and need to keep the original tuple object intact.

Fix 2: Using Slicing

Another way to change the values in a tuple is by using slicing. You can create a new tuple with the desired values by slicing the original tuple and concatenating the new values.

In this example, we use slicing to create a new tuple. The my_tuple[:0] slice returns an empty tuple, the (4,) creates a new tuple with the value 4, and the my_tuple[1:] slice returns a new tuple with all elements of the original tuple except the first element.

We then concatenate these three tuples using the + operator to create a new tuple with the desired values.

It’s important to note that the original tuple remains unchanged, and the new tuple is created with the modified values.

This method is useful when you want to make changes to the tuple and need to keep the original tuple object intact.

It is also worth noting that this method is the most efficient one of the three, as it only uses slicing which has O(k) time complexity where k is the number of elements in the slice.

Fix 3: Creating a new Tuple

The last fix is creating a new tuple with the desired values.

This method works similarly to the previous method, but instead of using slicing and concatenation, we create a new tuple with the desired value and concatenate it with the rest of the elements of the original tuple using the + operator.

While tuples are immutable in Python, there are a few ways to work around the ‘tuple’ object does not support item assignment error. By converting the tuple to a list, using slicing, or creating a new tuple, you can achieve the desired outcome.

We hope this article was useful.

You may also enjoy

New article

Python’s Default dict explained

4 minute read

In this article, we will explain how to use default dicts in the Python programming language. Find examples and more

C++ Undefined reference to std::cout

3 minute read

How to fix the undefined reference to std::cout in the C++ programming language. This error is usually caused by a dependency problem in the gcc compiler.

C++ Length of an Array With Examples (3 easy ways)

In this article, we will use sizeof() operator, for loop method and the std::size function to determine the length of any C++ array. We will provide examples

C++ Convert Int to String

1 minute read

How to convert an int to a string in C++, we will be using the to_string, stringstream and sprintf functions from the std library. Easiest methods to convert

TEchwithech.com

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.

解决python报错TypeError: ‘tuple‘ object does not support item assignment

typeerror 'tuple' object does not support item assignment in python

解决办法(两者取其一)

出现这个报错原因是操作的变量是元组,你给它修改值了。

比如下面我的代码返回的 res是元组类型 ,但我想改第二项的值为403,元组tuple是不允许直接修改元素值的,所以报错了。

1,想要改元素值,先转换类型为list即可,即返回res之后,先res=list(res)

2,创建一个同结构的列表,需要改的和不需要改的元组内的值对应放入list中,使用这个新的list即可

typeerror 'tuple' object does not support item assignment in python

“相关推荐”对你有帮助么?

typeerror 'tuple' object does not support item assignment in python

请填写红包祝福语或标题

typeerror 'tuple' object does not support item assignment in python

ProblemTerminator

您的鼓励将是作者最大的动力哦!

typeerror 'tuple' object does not support item assignment in python

您的余额不足,请更换扫码支付或 充值

typeerror 'tuple' object does not support item assignment in python

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

typeerror 'tuple' object does not support item assignment in python

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.

typeerror 'tuple' object does not support item assignment in python

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

How to Convert PNG to TIFF in Python?

How to Convert PNG to TIFF in Python?

Discover how to pivot a dataframe or table in Python Pandas

How to Pivot a DataFrame or Table in Python Pandas?

Index is out of bounds for axis 0 with size

How to Fix “IndexError: Index 0 is Out of Bounds for Axis 0 With Size 0” in Python?

How to fix SyntaxError missing parentheses in call to print

How to Fix the “ImportError: No Module Named” in Python?

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 library stubs not installed for requests error.

Library Stubs Not Installed for Requests: A Guide to Fixing the Error Have you ever tried to install a Python package and received the error “Library stubs not installed for requests”? If so, you’re not alone. This is a common error that can occur when you’re trying to install the Requests library, which is a…

How to Fix the execvp: No Such File or Directory Error

Have you ever tried to run a program on your computer, only to get an error message saying “execvp: no such file or directory”? If so, you’re not alone. This error message is a common one, and it can be caused by a variety of different factors. In this article, we’ll take a closer look…

Package org.junit does not exist: How to fix this error

JUnit Package Not Found: A Guide to Fixing This Error If you’re a Java developer, you’ve probably encountered the dreaded “package org.junit does not exist” error. This error can be caused by a variety of reasons, but it’s usually due to a simple mistake in your code. In this guide, we’ll walk you through how…

5 Ways to Fix the ReferenceError: XMLHttpRequest is not Defined

**Have you ever encountered the dreaded “ReferenceError: XMLHttpRequest is not defined” error?** If so, you’re not alone. This error is a common one, and it can be a real pain to troubleshoot. But don’t worry, we’re here to help. In this article, we’ll take a look at what the “ReferenceError: XMLHttpRequest is not defined” error…

Conda Error: Downloaded Bytes Did Not Match Content-Length

Have you ever encountered the dreaded “conda error: downloaded bytes did not match content-length” message? If so, you’re not alone. This error is a common one, and it can be frustrating to troubleshoot. But don’t worry, we’re here to help. In this article, we’ll explain what this error means and how to fix it. We’ll…

ModuleNotFoundError: No module named ‘ultralytics.utils’

ModuleNotFoundError: No module named ‘ultralytics.utils’ This error message is a common one for Python developers who are trying to use the Ultralytics library. It can be caused by a number of factors, but the most common is that the library is not installed correctly. In this article, we will take a look at what causes…

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)

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

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.

typeerror 'tuple' object does not support item assignment in python

Typeerror: ‘tuple’ object does not support item assignment

One of the errors we encounter, when we try to change the value of tuple item, is Typeerror: ‘tuple’ object does not support item assignment .

Furthermore in this guide, we will tackle why this error occurs, as well as practical example codes for better understanding.

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.

Why Typeerror: ‘tuple’ object does not support item assignment?

Every time we try to modify or assign a value to an element within a tuple using the assignment operator…

Essentially we are trying to change the content of an immutable object, which is not possible in Python.

Now that we understand what is this error and why this error occurs, let’s proceed to solutions to this error.

How to fix Typeerror: ‘tuple’ object does not support item assignment

Here are three possible solutions with example codes and their explanations.

Solution 1: Convert the tuple to a list and back to a tuple

One way to fix the error is to convert the tuple to a list, make the needed modifications, and then convert it back to a tuple.

Solution 2: Use tuple concatenation to create a new tuple

Here is an example code:

We then create a new tuple called new_tuple that contains the first and third elements of my_tuple and a modified value for the second element.

Solution 3: Use named tuples from the collections module

A third way to fix the error is to use named tuples from the collections module.

Thus, when you need to keep track of the meaning of each element.

Any of the approaches can fix the error depending on your error.

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 July 5, 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 Introduction
  • Python Fundamentals
  • Python Control Flow
  • Python Data Structures
  • Python Files
  • Python Essentials
  • Python Exercises
  • Python Networking
  • Python Programming
  • Python Exceptions
  • Interview Questions

'tuple' object does not support item assignment

The TypeError: 'tuple' object does not support item assignment is an error that arises when attempting to modify the value of an element within a tuple. Tuples, as immutable objects, exhibit the property of being unalterable after their initialization. Consequently, any effort to alter the contents of a tuple results in this error.

This inherent immutability ensures the integrity of the data contained within the tuple and facilitates the creation of data structures where data should remain fixed and constant throughout its lifecycle. Tuples in Python are immutable, meaning once they are created, you cannot change their elements.

Converting the tuple into a list

To resolve this particular error, a suitable approach involves converting the tuple into a list, as lists boast mutability, allowing the modification of their elements. By transforming the tuple into a list, the desired changes to the item can be performed seamlessly.

Once the necessary modifications are accomplished, the list can then be transformed back into a tuple, thus retaining the original immutability and ensuring the integrity of the data structure. This conversion process allows for a flexible and efficient means of addressing the issue without compromising the inherent properties of tuples.

This code will first create a tuple called tuple_data with the values 1, 2, and 3. Then, it will try to change the value of the first item in the tuple. This will raise an error because tuples are immutable objects.

Then, the code will convert the tuple to a list. Lists are mutable objects, so the value of the first item can be changed. The code then changes the value of the first item to 4. Finally, the code converts the list back to a tuple and prints the tuple.

Other Solutions:

Use a list instead of a tuple.

Lists in Python are mutable, so you can modify their elements after creation.

Create a new tuple with the modified elements

Since tuples are immutable, you can't change an element directly, but you can create a new tuple with the desired changes.

It is essential to bear in mind that tuples are typically employed to store data that is intended to remain unaltered throughout its existence, whereas lists are utilized for data that may require modification. The choice of data structure should align with the specific use case to ensure optimal performance and data integrity. Selecting the appropriate structure ensures that the data is appropriately managed, safeguarding its intended purpose and preventing unintended changes that could compromise its consistency.

  • TypeError: 'NoneType' object is not subscriptable
  • IndexError: string index out of range
  • IndentationError: unexpected indent Error
  • ValueError: too many values to unpack (expected 2)
  • SyntaxError- EOL while scanning string literal
  • TypeError: Can't convert 'int' object to str implicitly
  • IndentationError: expected an indented block
  • ValueError: invalid literal for int() with base 10
  • IndexError: list index out of range : Python
  • AttributeError: 'module' object has no attribute 'main'
  • UnboundLocalError: local variable referenced before assignment
  • TypeError: string indices must be integers
  • FileNotFoundError: [Errno 2] No such file or directory
  • Fatal error: Python.h: No such file or directory
  • ZeroDivisionError: division by zero
  • ImportError: No module named requests | Python
  • TypeError: 'NoneType' object is not iterable
  • SyntaxError: unexpected EOF while parsing | Python
  • zsh: command not found: python
  • Unicodeescape codec can't decode bytes in position 2-3
  • The AttributeError: 'bytes' object has no attribute 'read'

Online Tutorials & Training Materials | STechies.com

  • Learn Python Programming
  • Python Online Compiler
  • Python Training Tutorials for Beginners
  • Square Root in Python
  • Addition of two numbers in Python
  • Null Object in Python
  • Python vs PHP
  • TypeError: 'int' object is not subscriptable
  • pip is not recognized
  • Python Comment
  • Python Min()
  • Python Factorial
  • Python Continue Statement
  • Armstrong Number in Python
  • Python lowercase
  • Python Uppercase
  • Python map()
  • Python String Replace
  • Python String find
  • Python Max() Function
  • Invalid literal for int() with base 10 in Python
  • Top Online Python Compiler
  • Polymorphism in Python
  • Inheritance in Python
  • Python : end parameter in print()
  • Python String Concatenation
  • Python Pass Statement
  • Python Enumerate
  • Python New 3.6 Features
  • Python input()
  • Python String Contains
  • Python eval
  • Python zip()
  • Python Range
  • Install Opencv Python PIP Windows
  • Python String Title() Method
  • String Index Out of Range Python
  • Python Print Without Newline
  • Id() function in Python
  • Python Split()
  • Reverse Words in a String Python
  • Ord Function in Python
  • Only Size-1 Arrays Can be Converted to Python Scalars
  • Area of Circle in Python
  • Python Reverse String
  • Bubble Sort in Python
  • Attribute Error Python
  • Python Combine Lists
  • Python slice() function
  • Convert List to String Python
  • Python list append and extend
  • Python Sort Dictionary by Key or Value
  • indentationerror: unindent does not match any outer indentation level in Python
  • Remove Punctuation Python
  • Compare Two Lists in Python
  • Python Infinity
  • Python KeyError
  • Python Return Outside Function
  • Pangram Program in Python

TypeError: 'tuple' object does not support item assignment

Updated May 03, 2020

In this article, we will learn about the error TypeError: "tuple" object does not support item assignment . A tuple is a collection of ordered and unchangeable items as they are immutable . So once if a tuple is created we can neither change nor add new values to it.

The error “ TypeError: ‘tuple’ object does not support item assignment ” generates when we try to assign a new value in the tuple.

Let us understand it more with the help of an example.

In the above example in line 4 of the code, we are trying to assign a new value at index 2. Thus raising the error TypeError: 'tuple' object does not support item assignment .

To assign a new value in a tuple we can convert the tuple into a list, then after assigning convert the list back to the tuple as shown in the example below. Though it is recommended not to do so.

TypeError: 'tuple' object does not support item assignment

TypeError: 'numpy.float64' object does not support item assignment

The error in python called "TypeError: 'numpy. float64' object does not support item assignment" occurs when we try to assign a value to a numpy float using square brackets.

What is the error in Python Programming ?

There specific different types of error that we can encounter in python programming.

Now, the error in python called "TypeError: 'numpy. float64' object does not support item assignment" occurs when we try to assign a value to a numpy float using square brackets.

To solve the python error above, we will just correct the assignment or the accessor, as we can't mutate a floating-point number .

Read more about Python Error at; https://brainly.com/question/16074586

Related Questions

The Anglican Church in Africa tends to attract:

The main people who are attracted to the Anglican Church in Africa are the educated urban middle class.

A trend has been observed that the Anglican Church in Africa is generally attended by the middle class in the continent. These middle classes are often found in the urban and suburban areas.

The reason for this is unknown but it is theorized that the Anglican Church's association with the British is one reason. Another is that the Anglican Church may not have many branches in rural areas like the Catholic Church.

Find out more on the Anglican Church at https://brainly.com/question/4977644

11. If your vehicle begins to skid, you should:

If your vehicle begins to skid , you should: take your foot off the accelerator and steer in the direction of the skid.

A skid is an automobile handling condition where one or more tires are slipping relative to the road, and the overall handling of the vehicle has been affected.

The first thing that should be done when your vehicle begins to skid is to take your foot off the accelerator and steer in the direction of the skid .

Thus, If your vehicle begins to skid , you should: take your foot off the accelerator and steer in the direction of the skid.

Learn more about skid here: https://brainly.com/question/13387363

Click and drag the steps to determine whether the given graphs, described by their adjacency matrices, are isomorphic.

It should be noted that isomorphic graph is a graph that can exist in different forms and have the same number of vertices , edges, and edge connectivity.

You can say given graphs are isomorphic if they have:

In this case, two graphs are isomorphic if their complement graphs if their adjacency matrices are the same.

Therefore, isomorphic graph is a graph that can exist in different forms and have the same number of vertices , edges, and edge connectivity.

Learn more about graph on:

https://brainly.com/question/19040584

Which weak acid would be best to use when preparing a buffer solution with a pH of 8.70

The weak acid that would be best used when preparing a buffer solution would be An acid with Ka = 2.1 x 10-9

In chemistry, an acid is used to denote any substances that has the power to turn a litmus paper red and also has a sour taste when in a water solution.

How to solve for the weak acid

The pH needed for the buffer to be made is given as 8.7

We have the following equation

-logKa = 8.7

Such that Ka = 10^-87

= 2.1 x 10^-9

Read more on acids here: https://brainly.com/question/25148363

Economists argue that restrictions against ticket scalping actually drive up the cost of many tickets.

When it comes to economists believing that restrictions on ticket scalping increase the cost of tickets, this is TRUE .

Even though ticket scalping increases the price of tickets , if there wasn't any, economists believe that prices would be higher.

This is because ticket scalpers are at least putting the tickets on the market which leads to a lower price than if the tickets were not available at all but were still being demanded for.

Find out more on ticket scalping at https://brainly.com/question/5355255

Modify the RetirementGoal application from Chapter 6 Exercise 10A to display the amount of money the user will have if the user earns 4% interest on the balance every year.

Using the computational knowledge in python it is possible to write a code that makes a balance function per year from a gain of 4%

import java.util.Scanner;

public class RetirementGoal2 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

double savings;

System.out.println("Number of years the user has until retirement");

years = s.nextInt();

while (years <= 0) {

System.out.println("Please enter a valid number");

System.out.println("Enter amount of money you can save actually");

savings = s.nextDouble();

while (savings <= 0) {

double amount = 0;

// calculating the amount after given years and with 4% interest

for (int i = 1; i < years; i++) {

amount += savings;

amount *= 1.04;

//printing result

System.out.printf("Amount after " + years + " years : %.2f" , amount);

See more about JAVA at  brainly.com/question/12975450

Which of the following is NOT one of the main three types of driving environments

The on that cannot be classified as a main driving environment is parking lots .

This is a place designed for people to drive . Some examples of driving environments includes rural areas and cities because these usually have roads , streets , etc. for people to move on their cars .

A parking lot is not a driving environment because this is not designed for people to drive but only for people to leave their cars for some hours .

Note : This question is incomplete; here are the missing options:

Parking lots

Learn more about parking lots in: https://brainly.com/question/23045801

Mr. Gomez notes that a Private Fee-for-Service (PFFS) plan available in his area has an attractive premium

What you may have to tell Mr. Gomez would be that he can make use of any doctors in the country that is able to bill Medicare.

He has to ensure that he shows the doctor certain proof of the identification card of the plan that he is on.

This would be before the doctor would agree to accept the Private Fee-for-Service (PFFS) plan.

This term is used to refer to the income amount that a person has to spend on the payment for insurance. The premiums are paid over healthcare , automobiles, homes, and other properties.

The premium  insurance basically tells of the amount that a person has to pay in terms of insurance every month. You also have to pay other forms of deductibles and other costs for the insurance coverag e that you have.

Read more on the premium insurance here:

https://brainly.com/question/1191977

A store carries a wide variety of products such as clothes, furniture, and housewares, usually at higher prices than discount stores.

A store with a wide variety of products, usually at higher prices than discount stores is called a department store.

As this business configuration focuses on the sale of a variety of products that are easily marketed , the greatest advantages are the variety of products that generate consumer convenience , in addition to reduced advertising costs and economies of scale .

The disadvantages of a department store are related to the need for a high amount of capital to operate the business, in addition to promoting little personal contact with the end customer. But if organizational resources are well managed , this business structure can be very profitable .

Therefore, department stores are a trade whose focus is on the sale of varied products at a more competitive price and quality service, generating convenience and reliability for the consumer.

Find out more about department store here:

https://brainly.com/question/27293552

The student's lab manual says to mix 50 mL of his 2.0 M CaCl2 solution with 50 mL of a 3.0 M aqueous solution of sodium carbonate (Na2CO3). (18 points) i. Write a balanced chemical equation to show the reaction. Include state symbols. (4 points)

The balanced equation for the reaction is [tex]CaCl_2 (aq) + Na_2CO_3 (aq) --- > CaCO_3 (s) + 2NaCl (aq)[/tex]

Both calcium chloride and sodium carbonate are soluble salts. When they react, insoluble calcium carbonate is produced along with soluble sodium chloride.

The balanced equation of the reaction along with the state of each component is as follows:

  [tex]CaCl_2 (aq) + Na_2CO_3 (aq) --- > CaCO_3 (s) + 2NaCl (aq)[/tex]

More on chemical equations can be found here: https://brainly.com/question/12047033

A performance marketer wants to drive as much purchase value as possible within a specific return on ad spend. Which type of automated bidding strategy should the marketer use?

A performance marketer wants to drive as much purchase value as possible within a specific return on ad spend. The marketer use is revenue-focused bidding strategy called tROAs

tROAs automated bidding strategy is used when an individual is expected to make certain amount of profit on ads .

It helps to increase purchase value and in turn the revenue.

A performance marketer wants to drive as much purchase value as possible within a specific return on ad spend. The marketer use is revenue-focused bidding strategy called tROAs.

Learn more on marketing below

https://brainly.com/question/25369230

If the electrical potential in a region is constant, the electric field must be zero everywhere in that region.

False , if the electrical potential in a region is constant, the electric field must be zero everywhere in that region.

Electric field is the region of space where the influence of electric force is felt.

Thus, if the electrical potential in a region is constant, the electric field must vary with distance .

Learn more about electric field here: https://brainly.com/question/14372859

Renata needs to fill an open position in her department. In what situation should she use the nine-box grid

The situation in which she should use the nine-box grid is; d. If she wants to promote from within

The correct option that i would recommend that she should use the 9 box grid if she wants to recruit minorities.

Now, the The 9 box grid is a popular talent management tool whereby employees are divided into nine groups, based on their performance and potential.

When assessing employee performance , managers usually pay attention to how well they perform today also how well they are likely to perform in the future which signifies their growth potential.

Now, in this case, she wants to fill an open position in her department and as such looking at the given options and the definition of nine box grid above, it is clear that the correct option

The missing options are;

a. If she wants to avoid a glass-ceiling audit

b. If she wants to recruit minorities

c. If she needs to fill an entry-level position

d. If she wants to promote from within

Read more about human resource at; https://brainly.com/question/14642798

a nurse is assessing the development of a 3 year old child . which of the following gross motor skills should the nurse expect the child to be able to perform

The gross motor skill that the nurse should expect the child to be able to perform is:

A. Stacking 10 blocks

Gross motor skills are those types of skills that relate to the usage of the muscles, arms, legs, and torso . By age three, a preschooler's muscles should be developed well enough to stack 10 toy blocks together.

Their gross motor skills allow them to stretch and also allow them enough flexibility to fix the blocks properly. So, option A is right.

Learn more about gross motor skills here:

https://brainly.com/question/20292222

Complete Question:

A nurse is assessing a 3 year old preschooler. Which of the following developmental milestones should the nurse expect the preschooler to demonstrate.

B. Printing 1 letter

C. Tying shoelaces

D. Using 7 word sentences

One or more variables have a variance greater than the maximum allowed of 1000000. Check your data and format statement or rescale the variable(s) using the DEFINE command.

The most likely solution to your problem is that the data contains large numbers and to fix this, Mplus needs you to rescale the variables.

This refers to the act of finding and fixing errors in a program to allow it to run effectively.

Therefore, the error message you are getting while trying to import your data from SPSS to Mplus means that the data is too large and thus, you need to rescale the variables , which would still keep your estimates accurate.

Read more about debugging here:

https://brainly.com/question/15079851

Ronald is calculating the density of oranges in a crate. He knows the number of oranges in the crate and the volume of the crate. Which of the following formulas can be used to calculate the density of oranges in the crate

The density can be calculated by dividing the total number of oranges by the volume of the crate. The second option is the correct one.

As far as the population of something is concerned, the density is the ratio of the total population and the area covered by the population.

In this case, the density would be the ratio of the total number of oranges and the total area or volume the oranges occupy in the crate.

More on density can be found here: https://brainly.com/question/15164682

Density = volume of crate over number of oranges

Density = number of oranges over volume of crate

Volume of shelf = density over number of oranges

Number of books = density over volume of crate

Which linear function has the greatest y-intercept

From the given options of linear graph and linear equations, the linear function that has the greatest y-intercept is; y = 3x + 4

The y-intercept simply means the value of y in a linear equation at which x = 0 or the value of where where the graph crosses the y-axis.

Now, the general form of equation of a line in slope intercept form is given by; y = mx + c

c is y-intercept

1) The fist equation is; y = 6x + 1

Thus, comparing it to y = mx + c, we can say that;

Slope = 6 and y-intercept = 1

2) From the graph the line crosses the y-axis at y = 2 and as such we can say that the y-intercept is y = 2

3) From the graph the line crosses the y-axis at y = -3 and as such we can say that the y-intercept is y = -3

4) The fist equation is; y = 3x + 4

Slope = 3 and y-intercept = 4

Thus, looking at all the values of the y-intercepts , the linear function that has the greatest y-intercept is y = 3x + 4

Read more about y-intercept at; https://brainly.com/question/1884491

by what percent will a fraction change if its numerator is decreased by 60

it doesn't change or it will change by 0%

Humans fit into the food pyramid as ________.

Humans fit into the food pyramid as tertiary consumer

Food pyramid consist of many food web joined together.

Each food web consist of organisms in different energy group feeding directly on each other. The highest of the pyramid is Tertiary consumer .

Humans are tertiary consumer as they get their food by feeding on already available food.

Therefore, Humans fit into the food pyramid as tertiary consumer

Learn more on food pyramid below

https://brainly.com/question/14215982

Which statement is an example of one that must appear on advertisements for educational events

The statement that must appear in advertisements for educational events is:

The statement above should appear in advertisements for educational events because such programs are designed to include everyone despite any limitations they might have. Educators know the importance of diversity.

There is no discrimination when it comes to knowledge so instructors endeavor to accommodate as many people as possible in their programs. This is why provisions will be made for people with special needs.

Learn more about advertisements here:

https://brainly.com/question/1658517

Which statement is an example of one that must appear on advertisements for educational events?

Which of the following scenarios involves the administration of ALS

We can actually deduce here that the scenario that involves the administration of ALS is: C. A 48-year-old patient whose airway is secured with a supraglottic device.

ALS means Advanced Life Support. It actually refers to the basic life support given to people that needs oxygen and chest compressions. It relies on monitoring the electrical activities of the heart.

The options that complete the question are:

A. A 53-year-old patient who is assisted with his prescribed nitroglycerin

B. A 61-year-old patient who is receiving humidified supplemental oxygen

C. A 48-year-old patient whose airway is secured with a supraglottic device

D. A 64-year-old patient who is given aspirin for suspected cardiac chest pain.

We see here that option C is the correct answer that gives the scenario that involves the administration of ALS.

Learn more about A d v a n c e d L i f e Support on https://brainly.com/question/24217740

which term describes a relationship between the national government and the states in which the national government directs the states on policies they must follow

The term that describes a relationship between the national government and the states in which the national government directs the states on policies they must follow is coercive .

In a coercive relationship between national and state government , it usually refers to a pattern of behaviors used by a higher authority to control their partner and create an uneven power dynamic.

In a coercive relationship between national and state government, the national government directs the states on policies they must follow.

Thus, the term that describes a relationship between the national government and the states in which the national government directs the states on policies they must follow is coercive .

Learn more about coercive relationship here: https://brainly.com/question/4179403

Participants in the early music movement value all performances except those that are:

Participants in the early music movement typically value all performances except those that were: played before noontime .

The Classic period orchestra was an era in which musical instruments comprised strings, brass, woodwinds, and percussion and all music composition were written out separately, so as to enable smooth performances .

Based on historical records and information, we can infer and logically deduce that participants in the early music movement such as the Classic period orchestra , typically value all performances except those that were played before noontime (12 PM).

Read more on Classic period orchestra here: https://brainly.com/question/14125371

This excerpt exemplifies how Hemingway uses short sentences that are still loaded with meaning. contain very little more meaning. are purposefully difficult to understand. hold limited symbolic value.

This excerpt exemplifies how Hemingway uses short sentences that are A. still loaded with meaning.

This refers to the use of words to communicate to another person that contains a subject and predicate.

Hence, we can see that from the complete text , there is the narration by Ernest Hemingway where Passini uses a monologue of short sentences to talk about defeat and death and these are still loaded with meaning.

Read more about Ernest Hemingway here:

https://brainly.com/question/7829599

Explanation:

the area of an irregular shape is found by dividing the shape into polygons with gaps between them

The area of an irregular shape can be found by dividing the shape into polygons with gaps between them: True.

A polygon is a two-dimensional geometric shape that comprises straight line segments and a finite number of sides . Also, some examples of a polygon include the following:

In Geometry, the area of an irregular shape can be found by dividing the shape into polygons with gaps between them and then add their areas together.

Read more on polygon here: https://brainly.com/question/16691874

Richard III was positively identified by both the morphology of the skeleton and comparison of DNA sampled from a living relative.

The statement ' Richard III was positively identified by both the morphology of the skeleton and comparison of DNA sampled from a living relative ' is TRUE.

Richard III was King of England from 1483 to 1485 (he died in the Battle of Bosworth on 22 August 1485).

Richard III was identified by an analysis of DNA , which is based on the linear order of nucleotide bases in the genome.

In conclusion, the statement ' Richard III was positively identified by both the morphology of the skeleton and comparison of DNA sampled from a living relative ' is TRUE.

Learn more about Richard III here:

https://brainly.com/question/2170706

Which of the following is true about hypnosis?

It is true people will do anything under hypnosis. Option A is correct

This is a condition when an individual action and in-action cannot be controlled by himself.

The person begin to act under a strong influence as he or she is bid. Also, the individual is not conscious of his environment or actions but rather act irrationally that is why it is very easy to do things that are u n sual and such that an individual may not do ordinarily under hypnosis.

Hypnosis is usually done by therapist through constant repetition of certain words and it makes the individual calm this is because it deals with mental health.

It is true people will do anything under hypnosis.

Learn more on hypnosis below

https://brainly.com/question/2378401

which of the following statements concerning hypnosis is true? a. people will do anything under hypnosis b. hypnosis is the same as sleeping

is-324.a community hurricane preparedness answers

The steps that can be taken by a  community to prepare for hurricane are:

Hurricane which can be regarded as the rapidly rotating storm system which usually have a low-pressure center can be prepared for by following the above measures.

Learn more about hurricane at

https://brainly.com/question/5704749

Ignoring the effects of friction, what is the mechanical advantage of using the ramp as opposed to lifting the gurney straight up

The mechanical advantage of using the ramp is given as   2.

The formula for Mechanical advantage is given as

hypotenuse / height

and also weight of object /force

The ratio of the right angled triangle is going to be

x : x√3 : 2x. Thus:

When this is rewritten , we would have

MA = 2x / x = 2

In physics, the mechanical advantage is used to refer to the ratio of a force produced by a given machine to the force that was applied to that particular machine. This is the advantage that is gained by the fact that a mechanism is used to transmit force.

The assumption that is made would be that no friction would be in existence that may cause any forms of alterations in the system.

Hence we conclude that the MA in the system is given as 2.

Read more on mechanical advantage here:

https://brainly.com/question/18345299

the accompanying graph depicts demand at point d demand is

The accompanying graph depicts demand At point A, demand is: A)The accompanying graph depicts demand.

It depict the demands of goods at at that point.

CHECK THE COMPLETE QUESTION:

The accompanying graph depicts demand at point d demand:

A) unit elastic.

B) inelastic.

C) elastic.

D) perfectly elastic.

Learn more about demand on:

https://brainly.com/question/25220385

  • Instructor View

Short Introduction to Programming in Python

Last updated on 2024-02-21 | Edit this page

  • How do I program in Python?
  • How can I represent my data in Python?
  • Describe the advantages of using programming vs. completing repetitive tasks by hand.
  • Define the following data types in Python: strings, integers, and floats.
  • Perform mathematical operations in Python using basic operators.
  • Define the following as it relates to Python: lists, tuples, and dictionaries.

Interpreter

Python is an interpreted language which can be used in two ways:

  • “Interactively”: when you use it as an “advanced calculator” executing one command at a time. To start Python in this mode, execute python on the command line:

Chevrons >>> indicate an interactive prompt in Python, meaning that it is waiting for your input.

  • “Scripting” Mode: executing a series of “commands” saved in text file, usually with a .py extension after the name of your file:

Introduction to variables in Python

Assigning values to variables.

One of the most basic things we can do in Python is assign values to variables:

Here we’ve assigned data to the variables text , number and pi_value , using the assignment operator = . To review the value of a variable, we can type the name of the variable into the interpreter and press Return :

Everything in Python has a type. To get the type of something, we can pass it to the built-in function type :

The variable text is of type str , short for “string”. Strings hold sequences of characters, which can be letters, numbers, punctuation or more exotic forms of text (even emoji!).

We can also see the value of something using another built-in function, print :

This may seem redundant, but in fact it’s the only way to display output in a script:

Running the script

Notice that “Data Carpentry” is printed only once.

Tip : print and type are built-in functions in Python. Later in this lesson, we will introduce methods and user-defined functions. The Python documentation is excellent for reference on the differences between them.

Tip : When editing scripts like example.py , be careful not to use word processors such as MS Word, as they may introduce extra information that confuses Python. In this lesson we will be using either Jupyter notebooks or the Spyder IDE, and for your everyday work you may also choose any text editor such as Notepad++, VSCode, Vim, or Emacs.

We can perform mathematical calculations in Python using the basic operators +, -, /, *, % :

We can also use comparison and logic operators: <, >, ==, !=, <=, >= and statements of identity such as and, or, not . The data type returned by this is called a boolean .

Sequences: Lists and Tuples

Lists are a common data structure to hold an ordered sequence of elements. Each element can be accessed by an index. Note that Python indexes start with 0 instead of 1:

A for loop can be used to access the elements in a list or other Python data structure one at a time:

Indentation is very important in Python. Note that the second line in the example above is indented. Just like three chevrons >>> indicate an interactive prompt in Python, the three dots ... are Python’s prompt for multiple lines. This is Python’s way of marking a block of code. [Note: you do not type >>> or ... .]

To add elements to the end of a list, we can use the append method. Methods are a way to interact with an object (a list, for example). We can invoke a method using the dot . followed by the method name and a list of arguments in parentheses. Let’s look at an example using append :

To find out what methods are available for an object, we can use the built-in help command:

A tuple is similar to a list in that it’s an ordered sequence of elements. However, tuples can not be changed once created (they are “immutable”). Tuples are created by placing comma-separated values inside parentheses () .

Tuples vs. Lists

  • What happens when you execute a_list[1] = 5 ?
  • What happens when you execute a_tuple[2] = 5 ?
  • What does type(a_tuple) tell you about a_tuple ?
  • What information does the built-in function len() provide? Does it provide the same information on both tuples and lists? Does the help() function confirm this?

Show me the solution

The second value in a_list is replaced with 5 .

As a tuple is immutable, it does not support item assignment. Elements in a list can be altered individually.

The function tells you that the variable a_tuple is an object of the class tuple .

len() tells us the length of an object. It works the same for both lists and tuples, providing us with the number of entries in each case.

Lists and tuples are both types of container i.e. objects that can contain multiple items, the key difference being that lists are mutable i.e. they can be modified after they have been created, while tuples are not: their value cannot be modified, only overwritten.

Dictionaries

A dictionary is a container that holds pairs of objects - keys and values.

Dictionaries work a lot like lists - except that you index them with keys . You can think about a key as a name or unique identifier for the value it corresponds to.

To add an item to the dictionary we assign a value to a new key:

Using for loops with dictionaries is a little more complicated. We can do this in two ways:

Changing dictionaries

  • First, print the value of the rev dictionary to the screen.
  • Reassign the value that corresponds to the key second so that it no longer reads “two” but instead 2 .
  • Print the value of rev to the screen again to see if the value has changed.

Defining a section of code as a function in Python is done using the def keyword. For example a function that takes two arguments and returns their sum can be defined as:

  • Python is an interpreted language which can be used interactively (executing one command at a time) or in scripting mode (executing a series of commands saved in file).
  • One can assign a value to a variable in Python. Those variables can be of several types, such as string, integer, floating point and complex numbers.
  • Lists and tuples are similar in that they are ordered lists of elements; they differ in that a tuple is immutable (cannot be changed).
  • Dictionaries are data structures that provide mappings between keys and values.

Navigazione

  • successivo |
  • precedente |
  • Python »
  • 3.14.0a0 Documentation »
  • Extending and Embedding the Python Interpreter »
  • 1. Extending Python with C or C++
  • Theme Auto Light Dark |

1. Extending Python with C or C++ ¶

It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h" .

The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters.

The C extension interface is specific to CPython, and extension modules do not work on other Python implementations. In many cases, it is possible to avoid writing C extensions and preserve portability to other implementations. For example, if your use case is calling C library functions or system calls, you should consider using the ctypes module or the cffi library rather than writing custom C code. These modules let you write Python code to interface with C code and are more portable between implementations of Python than writing and compiling a C extension module.

1.1. A Simple Example ¶

Let’s create an extension module called spam (the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function system() [ 1 ] . This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:

Begin by creating a file spammodule.c . (Historically, if a module is called spam , the C file containing its implementation is called spammodule.c ; if the module name is very long, like spammify , the module name can be just spammify.c .)

The first two lines of our file can be:

which pulls in the Python API (you can add a comment describing the purpose of the module and a copyright notice if you like).

Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

#define PY_SSIZE_T_CLEAN was used to indicate that Py_ssize_t should be used in some APIs instead of int . It is not necessary since Python 3.13, but we keep it here for backward compatibility. See Strings and buffers for a description of this macro.

All user-visible symbols defined by Python.h have a prefix of Py or PY , except those defined in standard header files. For convenience, and since they are used extensively by the Python interpreter, "Python.h" includes a few standard header files: <stdio.h> , <string.h> , <errno.h> , and <stdlib.h> . If the latter header file does not exist on your system, it declares the functions malloc() , free() and realloc() directly.

The next thing we add to our module file is the C function that will be called when the Python expression spam.system(string) is evaluated (we’ll see shortly how it ends up being called):

There is a straightforward translation from the argument list in Python (for example, the single expression "ls -l" ) to the arguments passed to the C function. The C function always has two arguments, conventionally named self and args .

The self argument points to the module object for module-level functions; for a method it would point to the object instance.

The args argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call’s argument list. The arguments are Python objects — in order to do anything with them in our C function we have to convert them to C values. The function PyArg_ParseTuple() in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values. More about this later.

PyArg_ParseTuple() returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can return NULL immediately (as we saw in the example).

1.2. Intermezzo: Errors and Exceptions ¶

An important convention throughout the Python interpreter is the following: when a function fails, it should set an exception condition and return an error value (usually -1 or a NULL pointer). Exception information is stored in three members of the interpreter’s thread state. These are NULL if there is no exception. Otherwise they are the C equivalents of the members of the Python tuple returned by sys.exc_info() . These are the exception type, exception instance, and a traceback object. It is important to know about them to understand how errors are passed around.

The Python API defines a number of functions to set various types of exceptions.

The most common one is PyErr_SetString() . Its arguments are an exception object and a C string. The exception object is usually a predefined object like PyExc_ZeroDivisionError . The C string indicates the cause of the error and is converted to a Python string object and stored as the «associated value» of the exception.

Another useful function is PyErr_SetFromErrno() , which only takes an exception argument and constructs the associated value by inspection of the global variable errno . The most general function is PyErr_SetObject() , which takes two object arguments, the exception and its associated value. You don’t need to Py_INCREF() the objects passed to any of these functions.

You can test non-destructively whether an exception has been set with PyErr_Occurred() . This returns the current exception object, or NULL if no exception has occurred. You normally don’t need to call PyErr_Occurred() to see whether an error occurred in a function call, since you should be able to tell from the return value.

When a function f that calls another function g detects that the latter fails, f should itself return an error value (usually NULL or -1 ). It should not call one of the PyErr_* functions — one has already been called by g . f ’s caller is then supposed to also return an error indication to its caller, again without calling PyErr_* , and so on — the most detailed cause of the error was already reported by the function that first detected it. Once the error reaches the Python interpreter’s main loop, this aborts the currently executing Python code and tries to find an exception handler specified by the Python programmer.

(There are situations where a module can actually give a more detailed error message by calling another PyErr_* function, and in such cases it is fine to do so. As a general rule, however, this is not necessary, and can cause information about the cause of the error to be lost: most operations can fail for a variety of reasons.)

To ignore an exception set by a function call that failed, the exception condition must be cleared explicitly by calling PyErr_Clear() . The only time C code should call PyErr_Clear() is if it doesn’t want to pass the error on to the interpreter but wants to handle it completely by itself (possibly by trying something else, or pretending nothing went wrong).

Every failing malloc() call must be turned into an exception — the direct caller of malloc() (or realloc() ) must call PyErr_NoMemory() and return a failure indicator itself. All the object-creating functions (for example, PyLong_FromLong() ) already do this, so this note is only relevant to those who call malloc() directly.

Also note that, with the important exception of PyArg_ParseTuple() and friends, functions that return an integer status usually return a positive value or zero for success and -1 for failure, like Unix system calls.

Finally, be careful to clean up garbage (by making Py_XDECREF() or Py_DECREF() calls for objects you have already created) when you return an error indicator!

The choice of which exception to raise is entirely yours. There are predeclared C objects corresponding to all built-in Python exceptions, such as PyExc_ZeroDivisionError , which you can use directly. Of course, you should choose exceptions wisely — don’t use PyExc_TypeError to mean that a file couldn’t be opened (that should probably be PyExc_OSError ). If something’s wrong with the argument list, the PyArg_ParseTuple() function usually raises PyExc_TypeError . If you have an argument whose value must be in a particular range or must satisfy other conditions, PyExc_ValueError is appropriate.

You can also define a new exception that is unique to your module. For this, you usually declare a static object variable at the beginning of your file:

and initialize it in your module’s initialization function ( PyInit_spam() ) with an exception object:

Note that the Python name for the exception object is spam.error . The PyErr_NewException() function may create a class with the base class being Exception (unless another class is passed in instead of NULL ), described in Built-in Exceptions .

Note also that the SpamError variable retains a reference to the newly created exception class; this is intentional! Since the exception could be removed from the module by external code, an owned reference to the class is needed to ensure that it will not be discarded, causing SpamError to become a dangling pointer. Should it become a dangling pointer, C code which raises the exception could cause a core dump or other unintended side effects.

We discuss the use of PyMODINIT_FUNC as a function return type later in this sample.

The spam.error exception can be raised in your extension module using a call to PyErr_SetString() as shown below:

1.3. Back to the Example ¶

Going back to our example function, you should now be able to understand this statement:

It returns NULL (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by PyArg_ParseTuple() . Otherwise the string value of the argument has been copied to the local variable command . This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable command should properly be declared as const char *command ).

The next statement is a call to the Unix function system() , passing it the string we just got from PyArg_ParseTuple() :

Our spam.system() function must return the value of sts as a Python object. This is done using the function PyLong_FromLong() .

In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!)

If you have a C function that returns no useful argument (a function returning void ), the corresponding Python function must return None . You need this idiom to do so (which is implemented by the Py_RETURN_NONE macro):

Py_None is the C name for the special Python object None . It is a genuine Python object rather than a NULL pointer, which means «error» in most contexts, as we have seen.

1.4. The Module’s Method Table and Initialization Function ¶

I promised to show how spam_system() is called from Python programs. First, we need to list its name and address in a «method table»:

Note the third entry ( METH_VARARGS ). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be METH_VARARGS or METH_VARARGS | METH_KEYWORDS ; a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.

When using only METH_VARARGS , the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via PyArg_ParseTuple() ; more information on this function is provided below.

The METH_KEYWORDS bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third PyObject * parameter which will be a dictionary of keywords. Use PyArg_ParseTupleAndKeywords() to parse the arguments to such a function.

The method table must be referenced in the module definition structure:

This structure, in turn, must be passed to the interpreter in the module’s initialization function. The initialization function must be named PyInit_name() , where name is the name of the module, and should be the only non- static item defined in the module file:

Note that PyMODINIT_FUNC declares the function as PyObject * return type, declares any special linkage declarations required by the platform, and for C++ declares the function as extern "C" .

When the Python program imports module spam for the first time, PyInit_spam() is called. (See below for comments about embedding Python.) It calls PyModule_Create() , which returns a module object, and inserts built-in function objects into the newly created module based upon the table (an array of PyMethodDef structures) found in the module definition. PyModule_Create() returns a pointer to the module object that it creates. It may abort with a fatal error for certain errors, or return NULL if the module could not be initialized satisfactorily. The init function must return the module object to its caller, so that it then gets inserted into sys.modules .

When embedding Python, the PyInit_spam() function is not called automatically unless there’s an entry in the PyImport_Inittab table. To add the module to the initialization table, use PyImport_AppendInittab() , optionally followed by an import of the module:

Removing entries from sys.modules or importing compiled modules into multiple interpreters within a process (or following a fork() without an intervening exec() ) can create problems for some extension modules. Extension module authors should exercise caution when initializing internal data structures.

A more substantial example module is included in the Python source distribution as Modules/xxmodule.c . This file may be used as a template or simply read as an example.

Unlike our spam example, xxmodule uses multi-phase initialization (new in Python 3.5), where a PyModuleDef structure is returned from PyInit_spam , and creation of the module is left to the import machinery. For details on multi-phase initialization, see PEP 489 .

1.5. Compilation and Linkage ¶

There are two more things to do before you can use your new extension: compiling and linking it with the Python system. If you use dynamic loading, the details may depend on the style of dynamic loading your system uses; see the chapters about building extension modules (chapter Building C and C++ Extensions ) and additional information that pertains only to building on Windows (chapter Building C and C++ Extensions on Windows ) for more information about this.

If you can’t use dynamic loading, or if you want to make your module a permanent part of the Python interpreter, you will have to change the configuration setup and rebuild the interpreter. Luckily, this is very simple on Unix: just place your file ( spammodule.c for example) in the Modules/ directory of an unpacked source distribution, add a line to the file Modules/Setup.local describing your file:

and rebuild the interpreter by running make in the toplevel directory. You can also run make in the Modules/ subdirectory, but then you must first rebuild Makefile there by running “ make Makefile”. (This is necessary each time you change the Setup file.)

If your module requires additional libraries to link with, these can be listed on the line in the configuration file as well, for instance:

1.6. Calling Python Functions from C ¶

So far we have concentrated on making C functions callable from Python. The reverse is also useful: calling Python functions from C. This is especially the case for libraries that support so-called «callback» functions. If a C interface makes use of callbacks, the equivalent Python often needs to provide a callback mechanism to the Python programmer; the implementation will require calling the Python callback functions from a C callback. Other uses are also imaginable.

Fortunately, the Python interpreter is easily called recursively, and there is a standard interface to call a Python function. (I won’t dwell on how to call the Python parser with a particular string as input — if you’re interested, have a look at the implementation of the -c command line option in Modules/main.c from the Python source code.)

Calling a Python function is easy. First, the Python program must somehow pass you the Python function object. You should provide a function (or some other interface) to do this. When this function is called, save a pointer to the Python function object (be careful to Py_INCREF() it!) in a global variable — or wherever you see fit. For example, the following function might be part of a module definition:

This function must be registered with the interpreter using the METH_VARARGS flag; this is described in section The Module’s Method Table and Initialization Function . The PyArg_ParseTuple() function and its arguments are documented in section Extracting Parameters in Extension Functions .

The macros Py_XINCREF() and Py_XDECREF() increment/decrement the reference count of an object and are safe in the presence of NULL pointers (but note that temp will not be NULL in this context). More info on them in section Reference Counts .

Later, when it is time to call the function, you call the C function PyObject_CallObject() . This function has two arguments, both pointers to arbitrary Python objects: the Python function, and the argument list. The argument list must always be a tuple object, whose length is the number of arguments. To call the Python function with no arguments, pass in NULL , or an empty tuple; to call it with one argument, pass a singleton tuple. Py_BuildValue() returns a tuple when its format string consists of zero or more format codes between parentheses. For example:

PyObject_CallObject() returns a Python object pointer: this is the return value of the Python function. PyObject_CallObject() is «reference-count-neutral» with respect to its arguments. In the example a new tuple was created to serve as the argument list, which is Py_DECREF() -ed immediately after the PyObject_CallObject() call.

The return value of PyObject_CallObject() is «new»: either it is a brand new object, or it is an existing object whose reference count has been incremented. So, unless you want to save it in a global variable, you should somehow Py_DECREF() the result, even (especially!) if you are not interested in its value.

Before you do this, however, it is important to check that the return value isn’t NULL . If it is, the Python function terminated by raising an exception. If the C code that called PyObject_CallObject() is called from Python, it should now return an error indication to its Python caller, so the interpreter can print a stack trace, or the calling Python code can handle the exception. If this is not possible or desirable, the exception should be cleared by calling PyErr_Clear() . For example:

Depending on the desired interface to the Python callback function, you may also have to provide an argument list to PyObject_CallObject() . In some cases the argument list is also provided by the Python program, through the same interface that specified the callback function. It can then be saved and used in the same manner as the function object. In other cases, you may have to construct a new tuple to pass as the argument list. The simplest way to do this is to call Py_BuildValue() . For example, if you want to pass an integral event code, you might use the following code:

Note the placement of Py_DECREF(arglist) immediately after the call, before the error check! Also note that strictly speaking this code is not complete: Py_BuildValue() may run out of memory, and this should be checked.

You may also call a function with keyword arguments by using PyObject_Call() , which supports arguments and keyword arguments. As in the above example, we use Py_BuildValue() to construct the dictionary.

1.7. Extracting Parameters in Extension Functions ¶

The PyArg_ParseTuple() function is declared as follows:

The arg argument must be a tuple object containing an argument list passed from Python to a C function. The format argument must be a format string, whose syntax is explained in Parsing arguments and building values in the Python/C API Reference Manual. The remaining arguments must be addresses of variables whose type is determined by the format string.

Note that while PyArg_ParseTuple() checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful!

Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count!

Some example calls:

1.8. Keyword Parameters for Extension Functions ¶

The PyArg_ParseTupleAndKeywords() function is declared as follows:

The arg and format parameters are identical to those of the PyArg_ParseTuple() function. The kwdict parameter is the dictionary of keywords received as the third parameter from the Python runtime. The kwlist parameter is a NULL -terminated list of strings which identify the parameters; the names are matched with the type information from format from left to right. On success, PyArg_ParseTupleAndKeywords() returns true, otherwise it returns false and raises an appropriate exception.

Nested tuples cannot be parsed when using keyword arguments! Keyword parameters passed in which are not present in the kwlist will cause TypeError to be raised.

Here is an example module which uses keywords, based on an example by Geoff Philbrick ( philbrick @ hks . com ):

1.9. Building Arbitrary Values ¶

This function is the counterpart to PyArg_ParseTuple() . It is declared as follows:

It recognizes a set of format units similar to the ones recognized by PyArg_ParseTuple() , but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python.

One difference with PyArg_ParseTuple() : while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally), Py_BuildValue() does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns None ; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.

Examples (to the left the call, to the right the resulting Python value):

1.10. Reference Counts ¶

In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. In C, this is done using the functions malloc() and free() . In C++, the operators new and delete are used with essentially the same meaning and we’ll restrict the following discussion to the C case.

Every block of memory allocated with malloc() should eventually be returned to the pool of available memory by exactly one call to free() . It is important to call free() at the right time. If a block’s address is forgotten but free() is not called for it, the memory it occupies cannot be reused until the program terminates. This is called a memory leak . On the other hand, if a program calls free() for a block and then continues to use the block, it creates a conflict with reuse of the block through another malloc() call. This is called using freed memory . It has the same bad consequences as referencing uninitialized data — core dumps, wrong results, mysterious crashes.

Common causes of memory leaks are unusual paths through the code. For instance, a function may allocate a block of memory, do some calculation, and then free the block again. Now a change in the requirements for the function may add a test to the calculation that detects an error condition and can return prematurely from the function. It’s easy to forget to free the allocated memory block when taking this premature exit, especially when it is added later to the code. Such leaks, once introduced, often go undetected for a long time: the error exit is taken only in a small fraction of all calls, and most modern machines have plenty of virtual memory, so the leak only becomes apparent in a long-running process that uses the leaking function frequently. Therefore, it’s important to prevent leaks from happening by having a coding convention or strategy that minimizes this kind of errors.

Since Python makes heavy use of malloc() and free() , it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting . The principle is simple: every object contains a counter, which is incremented when a reference to the object is stored somewhere, and which is decremented when a reference to it is deleted. When the counter reaches zero, the last reference to the object has been deleted and the object is freed.

An alternative strategy is called automatic garbage collection . (Sometimes, reference counting is also referred to as a garbage collection strategy, hence my use of «automatic» to distinguish the two.) The big advantage of automatic garbage collection is that the user doesn’t need to call free() explicitly. (Another claimed advantage is an improvement in speed or memory usage — this is no hard fact however.) The disadvantage is that for C, there is no truly portable automatic garbage collector, while reference counting can be implemented portably (as long as the functions malloc() and free() are available — which the C Standard guarantees). Maybe some day a sufficiently portable automatic garbage collector will be available for C. Until then, we’ll have to live with reference counts.

While Python uses the traditional reference counting implementation, it also offers a cycle detector that works to detect reference cycles. This allows applications to not worry about creating direct or indirect circular references; these are the weakness of garbage collection implemented using only reference counting. Reference cycles consist of objects which contain (possibly indirect) references to themselves, so that each object in the cycle has a reference count which is non-zero. Typical reference counting implementations are not able to reclaim the memory belonging to any objects in a reference cycle, or referenced from the objects in the cycle, even though there are no further references to the cycle itself.

The cycle detector is able to detect garbage cycles and can reclaim them. The gc module exposes a way to run the detector (the collect() function), as well as configuration interfaces and the ability to disable the detector at runtime.

1.10.1. Reference Counting in Python ¶

There are two macros, Py_INCREF(x) and Py_DECREF(x) , which handle the incrementing and decrementing of the reference count. Py_DECREF() also frees the object when the count reaches zero. For flexibility, it doesn’t call free() directly — rather, it makes a call through a function pointer in the object’s type object . For this purpose (and others), every object also contains a pointer to its type object.

The big question now remains: when to use Py_INCREF(x) and Py_DECREF(x) ? Let’s first introduce some terms. Nobody «owns» an object; however, you can own a reference to an object. An object’s reference count is now defined as the number of owned references to it. The owner of a reference is responsible for calling Py_DECREF() when the reference is no longer needed. Ownership of a reference can be transferred. There are three ways to dispose of an owned reference: pass it on, store it, or call Py_DECREF() . Forgetting to dispose of an owned reference creates a memory leak.

It is also possible to borrow [ 2 ] a reference to an object. The borrower of a reference should not call Py_DECREF() . The borrower must not hold on to the object longer than the owner from which it was borrowed. Using a borrowed reference after the owner has disposed of it risks using freed memory and should be avoided completely [ 3 ] .

The advantage of borrowing over owning a reference is that you don’t need to take care of disposing of the reference on all possible paths through the code — in other words, with a borrowed reference you don’t run the risk of leaking when a premature exit is taken. The disadvantage of borrowing over owning is that there are some subtle situations where in seemingly correct code a borrowed reference can be used after the owner from which it was borrowed has in fact disposed of it.

A borrowed reference can be changed into an owned reference by calling Py_INCREF() . This does not affect the status of the owner from which the reference was borrowed — it creates a new owned reference, and gives full owner responsibilities (the new owner must dispose of the reference properly, as well as the previous owner).

1.10.2. Ownership Rules ¶

Whenever an object reference is passed into or out of a function, it is part of the function’s interface specification whether ownership is transferred with the reference or not.

Most functions that return a reference to an object pass on ownership with the reference. In particular, all functions whose function it is to create a new object, such as PyLong_FromLong() and Py_BuildValue() , pass ownership to the receiver. Even if the object is not actually new, you still receive ownership of a new reference to that object. For instance, PyLong_FromLong() maintains a cache of popular values and can return a reference to a cached item.

Many functions that extract objects from other objects also transfer ownership with the reference, for instance PyObject_GetAttrString() . The picture is less clear, here, however, since a few common routines are exceptions: PyTuple_GetItem() , PyList_GetItem() , PyDict_GetItem() , and PyDict_GetItemString() all return references that you borrow from the tuple, list or dictionary.

The function PyImport_AddModule() also returns a borrowed reference, even though it may actually create the object it returns: this is possible because an owned reference to the object is stored in sys.modules .

When you pass an object reference into another function, in general, the function borrows the reference from you — if it needs to store it, it will use Py_INCREF() to become an independent owner. There are exactly two important exceptions to this rule: PyTuple_SetItem() and PyList_SetItem() . These functions take over ownership of the item passed to them — even if they fail! (Note that PyDict_SetItem() and friends don’t take over ownership — they are «normal.»)

When a C function is called from Python, it borrows references to its arguments from the caller. The caller owns a reference to the object, so the borrowed reference’s lifetime is guaranteed until the function returns. Only when such a borrowed reference must be stored or passed on, it must be turned into an owned reference by calling Py_INCREF() .

The object reference returned from a C function that is called from Python must be an owned reference — ownership is transferred from the function to its caller.

1.10.3. Thin Ice ¶

There are a few situations where seemingly harmless use of a borrowed reference can lead to problems. These all have to do with implicit invocations of the interpreter, which can cause the owner of a reference to dispose of it.

The first and most important case to know about is using Py_DECREF() on an unrelated object while borrowing a reference to a list item. For instance:

This function first borrows a reference to list[0] , then replaces list[1] with the value 0 , and finally prints the borrowed reference. Looks harmless, right? But it’s not!

Let’s follow the control flow into PyList_SetItem() . The list owns references to all its items, so when item 1 is replaced, it has to dispose of the original item 1. Now let’s suppose the original item 1 was an instance of a user-defined class, and let’s further suppose that the class defined a __del__() method. If this class instance has a reference count of 1, disposing of it will call its __del__() method.

Since it is written in Python, the __del__() method can execute arbitrary Python code. Could it perhaps do something to invalidate the reference to item in bug() ? You bet! Assuming that the list passed into bug() is accessible to the __del__() method, it could execute a statement to the effect of del list[0] , and assuming this was the last reference to that object, it would free the memory associated with it, thereby invalidating item .

The solution, once you know the source of the problem, is easy: temporarily increment the reference count. The correct version of the function reads:

This is a true story. An older version of Python contained variants of this bug and someone spent a considerable amount of time in a C debugger to figure out why his __del__() methods would fail…

The second case of problems with a borrowed reference is a variant involving threads. Normally, multiple threads in the Python interpreter can’t get in each other’s way, because there is a global lock protecting Python’s entire object space. However, it is possible to temporarily release this lock using the macro Py_BEGIN_ALLOW_THREADS , and to re-acquire it using Py_END_ALLOW_THREADS . This is common around blocking I/O calls, to let other threads use the processor while waiting for the I/O to complete. Obviously, the following function has the same problem as the previous one:

1.10.4. NULL Pointers ¶

In general, functions that take object references as arguments do not expect you to pass them NULL pointers, and will dump core (or cause later core dumps) if you do so. Functions that return object references generally return NULL only to indicate that an exception occurred. The reason for not testing for NULL arguments is that functions often pass the objects they receive on to other function — if each function were to test for NULL , there would be a lot of redundant tests and the code would run more slowly.

It is better to test for NULL only at the «source:» when a pointer that may be NULL is received, for example, from malloc() or from a function that may raise an exception.

The macros Py_INCREF() and Py_DECREF() do not check for NULL pointers — however, their variants Py_XINCREF() and Py_XDECREF() do.

The macros for checking for a particular object type ( Pytype_Check() ) don’t check for NULL pointers — again, there is much code that calls several of these in a row to test an object against various different expected types, and this would generate redundant tests. There are no variants with NULL checking.

The C function calling mechanism guarantees that the argument list passed to C functions ( args in the examples) is never NULL — in fact it guarantees that it is always a tuple [ 4 ] .

It is a severe error to ever let a NULL pointer «escape» to the Python user.

1.11. Writing Extensions in C++ ¶

It is possible to write extension modules in C++. Some restrictions apply. If the main program (the Python interpreter) is compiled and linked by the C compiler, global or static objects with constructors cannot be used. This is not a problem if the main program is linked by the C++ compiler. Functions that will be called by the Python interpreter (in particular, module initialization functions) have to be declared using extern "C" . It is unnecessary to enclose the Python header files in extern "C" {...} — they use this form already if the symbol __cplusplus is defined (all recent C++ compilers define this symbol).

1.12. Providing a C API for an Extension Module ¶

Many extension modules just provide new functions and types to be used from Python, but sometimes the code in an extension module can be useful for other extension modules. For example, an extension module could implement a type «collection» which works like lists without order. Just like the standard Python list type has a C API which permits extension modules to create and manipulate lists, this new collection type should have a set of C functions for direct manipulation from other extension modules.

At first sight this seems easy: just write the functions (without declaring them static , of course), provide an appropriate header file, and document the C API. And in fact this would work if all extension modules were always linked statically with the Python interpreter. When modules are used as shared libraries, however, the symbols defined in one module may not be visible to another module. The details of visibility depend on the operating system; some systems use one global namespace for the Python interpreter and all extension modules (Windows, for example), whereas others require an explicit list of imported symbols at module link time (AIX is one example), or offer a choice of different strategies (most Unices). And even if symbols are globally visible, the module whose functions one wishes to call might not have been loaded yet!

Portability therefore requires not to make any assumptions about symbol visibility. This means that all symbols in extension modules should be declared static , except for the module’s initialization function, in order to avoid name clashes with other extension modules (as discussed in section The Module’s Method Table and Initialization Function ). And it means that symbols that should be accessible from other extension modules must be exported in a different way.

Python provides a special mechanism to pass C-level information (pointers) from one extension module to another one: Capsules. A Capsule is a Python data type which stores a pointer ( void * ). Capsules can only be created and accessed via their C API, but they can be passed around like any other Python object. In particular, they can be assigned to a name in an extension module’s namespace. Other extension modules can then import this module, retrieve the value of this name, and then retrieve the pointer from the Capsule.

There are many ways in which Capsules can be used to export the C API of an extension module. Each function could get its own Capsule, or all C API pointers could be stored in an array whose address is published in a Capsule. And the various tasks of storing and retrieving the pointers can be distributed in different ways between the module providing the code and the client modules.

Whichever method you choose, it’s important to name your Capsules properly. The function PyCapsule_New() takes a name parameter ( const char * ); you’re permitted to pass in a NULL name, but we strongly encourage you to specify a name. Properly named Capsules provide a degree of runtime type-safety; there is no feasible way to tell one unnamed Capsule from another.

In particular, Capsules used to expose C APIs should be given a name following this convention:

The convenience function PyCapsule_Import() makes it easy to load a C API provided via a Capsule, but only if the Capsule’s name matches this convention. This behavior gives C API users a high degree of certainty that the Capsule they load contains the correct C API.

The following example demonstrates an approach that puts most of the burden on the writer of the exporting module, which is appropriate for commonly used library modules. It stores all C API pointers (just one in the example!) in an array of void pointers which becomes the value of a Capsule. The header file corresponding to the module provides a macro that takes care of importing the module and retrieving its C API pointers; client modules only have to call this macro before accessing the C API.

The exporting module is a modification of the spam module from section A Simple Example . The function spam.system() does not call the C library function system() directly, but a function PySpam_System() , which would of course do something more complicated in reality (such as adding «spam» to every command). This function PySpam_System() is also exported to other extension modules.

The function PySpam_System() is a plain C function, declared static like everything else:

The function spam_system() is modified in a trivial way:

In the beginning of the module, right after the line

two more lines must be added:

The #define is used to tell the header file that it is being included in the exporting module, not a client module. Finally, the module’s initialization function must take care of initializing the C API pointer array:

Note that PySpam_API is declared static ; otherwise the pointer array would disappear when PyInit_spam() terminates!

The bulk of the work is in the header file spammodule.h , which looks like this:

All that a client module must do in order to have access to the function PySpam_System() is to call the function (or rather macro) import_spam() in its initialization function:

The main disadvantage of this approach is that the file spammodule.h is rather complicated. However, the basic structure is the same for each function that is exported, so it has to be learned only once.

Finally it should be mentioned that Capsules offer additional functionality, which is especially useful for memory allocation and deallocation of the pointer stored in a Capsule. The details are described in the Python/C API Reference Manual in the section Capsules and in the implementation of Capsules (files Include/pycapsule.h and Objects/pycapsule.c in the Python source code distribution).

Table of Contents

  • 1.1. A Simple Example
  • 1.2. Intermezzo: Errors and Exceptions
  • 1.3. Back to the Example
  • 1.4. The Module’s Method Table and Initialization Function
  • 1.5. Compilation and Linkage
  • 1.6. Calling Python Functions from C
  • 1.7. Extracting Parameters in Extension Functions
  • 1.8. Keyword Parameters for Extension Functions
  • 1.9. Building Arbitrary Values
  • 1.10.1. Reference Counting in Python
  • 1.10.2. Ownership Rules
  • 1.10.3. Thin Ice
  • 1.10.4. NULL Pointers
  • 1.11. Writing Extensions in C++
  • 1.12. Providing a C API for an Extension Module

Argomento precedente

Extending and Embedding the Python Interpreter

Argomento successivo

2. Defining Extension Types: Tutorial

Questa pagina

  • Riporta un Bug
  • Visualizza codice
  • 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.

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

I'm writing a program to change ID by names, and I'm encountering the following problem

Vinne Benatti's user avatar

  • You cant assign a value to a tuple as they are not mutable. Try a list x = [['hi','hello'],['bye','adios']] –  Buddy Bob Commented Apr 28, 2022 at 1:12
  • 1 Hello @BuddyBob Thank you very much for the tip, I made the change and it worked correctly –  Vinne Benatti Commented Apr 28, 2022 at 1:20

With the help of BuddyBob, I managed to solve the problem, in case anyone has the same problem as me, below is the example of the code working:

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 list tuples or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Read an article about connecting a hot tub to a heat pump, looking for details
  • Are there any parts of the US Constitution that state that the laws apply universally to all citizens?
  • Seeing edges where there are no edges
  • Can the US president legally kill at will?
  • Are directed graphs with out-degree exactly 2 strongly connected with probability 1?
  • Why does `p` not put all yanked lines after quitting and reopening Vim?
  • Pregnancy in a hibernated state
  • Is a desert planet with a small habitable area possible?
  • If Mormonism is true and the apostasy started after Jesus' ascension why did God take so long to do something about it when Smith showed up in 1820?
  • Where is the pentagon in the Fibonacci sequence?
  • In-Place Reordering of Doubly Linked List Nodes to Ensure Memory Contiguity
  • How to have hashed shaded lines in TiKZ?
  • DH Encrypt by XOR
  • Has the Supreme Court given any examples where presumptive immunity would be overcome?
  • Does Justice Sotomayor's "Seal Team 6" example, in and of itself, explicitly give the President the authority to execute opponents? If not, why not?
  • Two definitions of a monad on an ∞-category
  • Does Salesforce Pro Suite allows you to do apex?
  • Does it make sense to use a skyhook to launch and deorbit mega-satellite constellations now?
  • Everything has a tiny nuclear reactor in it. How much of a concern are illegal nuclear bombs?
  • Product of expectation of two random variables
  • im2double and im2uint8 Functions Implementation for Image in C++
  • Is intuitionistic mathematics situated in time?
  • How shall I find the device of a phone's storage so that I can mount it in Linux?
  • Do you always experience the gravitational influence of other mass as you see them in your frame?

typeerror 'tuple' object does not support item assignment in python

IMAGES

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

    typeerror 'tuple' object does not support item assignment in python

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

    typeerror 'tuple' object does not support item assignment in python

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

    typeerror 'tuple' object does not support item assignment in python

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

    typeerror 'tuple' object does not support item assignment in python

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

    typeerror 'tuple' object does not support item assignment in python

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

    typeerror 'tuple' object does not support item assignment in python

VIDEO

  1. tuple syntax doesn't have parens (beginner

  2. "Debugging Python: How to Fix 'TypeError: unsupported operand types for + 'NoneType' and 'str'"

  3. 9. Tuples in Python: A Beginner's Guide

  4. 15- append item to a tuple in python

  5. How to Add an item in a tuple in Python

  6. I Learned Something New About Tuples In Python 3.11

COMMENTS

  1. python

    TypeError: 'tuple' object does not support item assignment I understand that this could be becuse badguy is a tuple. This means it is immutable(you can not change its values) Ive tried the following:

  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. TypeError: 'tuple' object does not support item assignment

    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 ...

  4. 'tuple' object does not support item assignment

    However I get this error: TypeError: 'tuple' object does not support item assignment python; python-imaging-library ... (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment In your specific case, as correctly pointed out in other answers, you should write: ... TypeError: 'tuple ...

  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])

  7. 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.

  8. Python Tuple does not support item assignment

    Python will raise a TypeError, indicating that the tuple object does not support item assignment. This is because, as previously mentioned, tuples are immutable, and their elements cannot be modified once they have been assigned.. Python's tuple is a built-in data structure that can store multiple values in a single object.

  9. 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:

  10. 解决python报错TypeError: 'tuple' object does not support item assignment

    TypeError: 'tuple' object does not support item assignment. 翻译: 类型错误:'tuple' 对象不支持项分配。 tuple 类型一旦初始化就不能修改,所以你要是修改它就会报错。 Python 修改tuple元组提示:TypeError: 'tuple' object does not support item assignment. 问题原因

  11. 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? Let's see how to fix it. MySQL; JavaScript; Python; ... 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 ...

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

    Marcus Greenwood Hatch, established in 2011 by Marcus Greenwood, has evolved significantly over the years. Marcus, a seasoned developer, brought a rich background in developing both B2B and consumer software for a diverse range of organizations, including hedge funds and web agencies.

  13. 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…

  14. 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.

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

    One of the errors we encounter, when we try to change the value of tuple item, is Typeerror: 'tuple' object does not support item assignment.

  16. "Fixing 'TypeError Tuple Object Does Not Support Item Assignment' Error

    #pythonforbeginners "Learn how to solve the 'TypeError Tuple Object Does Not Support Item Assignment' error in Python. This tutorial will guide you step-by-...

  17. 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.

  18. The TypeError: 'tuple' object does not support item assignment

    Once the necessary modifications are accomplished, the list can then be transformed back into a tuple, thus retaining the original immutability and ensuring the integrity of the data structure. This conversion process allows for a flexible and efficient means of addressing the issue without compromising the inherent properties of tuples.

  19. Python typeerror tuple object does not support item assignment

    Get Free GPT4o from https://codegive.com a `typeerror` with the message "tuple object does not support item assignment" is raised in python when you try to ...

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

    A tuple is a, TypeError: 'tuple' object does not support item assignment, Python Tutorial Register Login Python Photoshop SAP Java PHP Android C++ Hadoop Oracle Interview Questions Articles Other

  21. TypeError: 'numpy.float64' Object Does Not Support Item Assignment

    The gross motor skill that the nurse should expect the child to be able to perform is:. A. Stacking 10 blocks. What are gross motor skills? Gross motor skills are those types of skills that relate to the usage of the muscles, arms, legs, and torso.By age three, a preschooler's muscles should be developed well enough to stack 10 toy blocks together.. Their gross motor skills allow them to ...

  22. Python TypeError: 'type' object does not support item assignment

    Lot of issues here, I'll try to go through them one by one. The data structure dict = {} Not only is this overwriting python's dict, (see mgilson's comment) but this is the wrong data structure for the project.You should use a list instead (or a set if you have unique unordered values)

  23. Data Analysis and Visualization in Python for Ecologists: Short

    Define the following as it relates to Python: lists, tuples, and dictionaries. ... TypeError: 'tuple' object does not support item assignment. As a tuple is immutable, it does not support item assignment. Elements in a list can be altered individually. What does type(a_tuple) tell you about a_tuple? OUTPUT

  24. 1. Extending Python with C or C++

    It returns a new Python object, suitable for returning from a C function called from Python. One difference with PyArg_ParseTuple(): while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally), Py_BuildValue() does not always build a tuple. It builds a tuple only if its ...

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

    Python - TypeError: 'tuple' object is not callable Hot Network Questions Book that I read around 1975, where the main character is a retired space pilot hired to steal an object from a lab called Menlo Park