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

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

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

Consider the example below:

Solution #1: Change the tuple to list first

Solution #2: create a new tuple.

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

Take your skills to the next level ⚡️

CodeFatherTech

Learn to Code. Shape Your Future

Tuple Object Does Not Support Item Assignment. Why?

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

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

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

Let’s get started!

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

Define a tuple called cities as shown below:

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

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

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

There is a workaround to this, we can:

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

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

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

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

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

Makes sense?

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

The slicing operator also allows to avoid this error.

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

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

Here is the result we want:

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

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

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

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

First two elements

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

Last two elements

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

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

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

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

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

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

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

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

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

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

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

In Python, lists are mutable and tuples are immutable.

How to Solve This Error with a List of Tuples

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

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

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

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

How can we get around this error?

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

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

Let’s see if it works…

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

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

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

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

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

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

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

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

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

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

I get the following error…

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

Why Using Tuples If We Get This Error?

You might be thinking…

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

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

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

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

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

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

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

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

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

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

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

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

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

Related posts:

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

Leave a Comment Cancel reply

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

  • Privacy Overview
  • Strictly Necessary Cookies

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

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

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

Tech With Tech

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

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

You’ll learn:

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

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

Let’s jump right in!

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

Mutable, or Immutable? That Is the Question

Data types in Python are mutable or immutable .

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

You can write something like this:

Have you changed the variable a ? 

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

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

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

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

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

Mutable Data Types

More complex data types in Python are sequences such as: 

  • Byte Arrays

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

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

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

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

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

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

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

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

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

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

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

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

Concatenating a string with a tuple is not possible:

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

Or even like this:

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

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

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

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

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

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

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

Now you can change the average by student name:

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

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

This method is not very reliable by itself.

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

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

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

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

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

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

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

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

You can choose the design that you like best.

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

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

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

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

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

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

And this is a tuple!

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

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

For this, use the enumerate() function:

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

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

Here’s more Python support:

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

Theresa McDonough

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

The Research Scientist Pod

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

by Suf | Programming , Python , Tips

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

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

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

Table of contents

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

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

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

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

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

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

Let’s run the code to see the result:

We can successfully do item assignments on a list.

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

We throw the TypeError because the tuple object is immutable.

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

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

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

For further reading on TypeErrors, go to the article:

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

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

Have fun and happy researching!

Share this:

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

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.

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

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

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

What is Multiple Inheritance in Python?

What is Multiple Inheritance in Python?

Learn how to slice a dataframe in Pandas

How to Slice a Dataframe in Pandas?

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

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

  • Travel & Tourism
  • Beauty & Fashion

Logo

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

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

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

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

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

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

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

Does the tuple object support item assignment?

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

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

Logo

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 attributeerror: ‘dataframe’ object has no attribute ‘map’.

AttributeError: ‘DataFrame’ object has no attribute ‘map’ This error occurs when you try to call the `map()` function on a `DataFrame` object. The `map()` function is used to apply a function to each element of a sequence. However, the `DataFrame` object does not have a `map()` attribute, so you cannot call this function on it….

AttributeError: Entrypoints object has no attribute ‘get’

AttributeError: Entrypoints object has no attribute get Have you ever encountered the following error message: AttributeError: Entrypoints object has no attribute get If so, you’re not alone. This error is a common one, and it can be a bit tricky to troubleshoot. In this article, we’ll take a look at what causes this error and…

ModuleNotFoundError: No module named ‘transformers’

ModuleNotFoundError: No module named ‘transformers’ Have you ever tried to import the `transformers` module in Python and gotten an error message like `ModuleNotFoundError: No module named ‘transformers’`? If so, you’re not alone. This is a common error that can occur for a variety of reasons. In this article, we’ll take a look at what causes…

How to Fix the Can’t Convert np.ndarray of Type numpy.object_ Error

Can’t convert np.ndarray of type numpy.object_ Have you ever tried to convert a NumPy ndarray to another type, only to get an error message like “can’t convert np.ndarray of type numpy.object_”? If so, you’re not alone. This is a common error that can be caused by a number of things. In this article, we’ll take…

ValueError: Sample larger than population or is negative

Have you ever tried to take a sample from a population that was larger than the population itself? If so, you may have encountered a ValueError: sample larger than population or is negative error. This error occurs when you try to take a sample from a population that is either larger than the population itself…

ValueError: Mixing dicts with non-series may lead to ambiguous ordering

ValueError: Mixing dicts with non-series may lead to ambiguous ordering Data scientists and analysts often work with large datasets that contain a variety of data types. One common task is to merge two or more datasets together. However, if the datasets contain different data types, it is possible to get a ValueError error. This article…

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 September 12, 2024

Table of Content

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

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

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

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

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

1. TypeError

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

2. 'tuple' object does not support item assignment

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

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

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

Common Example Scenario

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

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

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

Break the code

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

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

Example solution

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

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

People are also reading:

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

Vinay

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

Related Blogs

7 Most Common Programming Errors Every Programmer Should Know

7 Most Common Programming Errors Every Programmer Should Know

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

Carbon Programming Language - A Successor to C++

Carbon Programming Language - A Successor to C++

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

Introduction to Elixir Programming Language

Introduction to Elixir Programming Language

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

Leave a Comment on this Post

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

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

Table of Contents

Getting Started With Python’s tuple Data Type

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

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

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

In this tutorial, you’ll learn how to:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Constructing Tuples in Python

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

  • Tuple literals
  • The tuple() constructor

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

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

Here’s the general syntax of a tuple literal:

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

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

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

Here are a few examples of creating tuples through literals:

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

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

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

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

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

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

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

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

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

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

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

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

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

Here’s the general syntax:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Here’s how this syntax works in practice:

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

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

“Jane Doe” 25 1.75 “Canada”

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

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

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

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

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

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

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

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

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

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

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

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

To illustrate, say that you have the following tuple:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Now go ahead and change the subject again:

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

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

Concatenating and Repeating Tuples

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

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

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

Here’s how it works:

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

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

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

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

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

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

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

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

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

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

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

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

Reversing and Sorting Tuples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Traversing Tuples in Python

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

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

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

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

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

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

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

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

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

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

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

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

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

Exploring Other Features of Tuples

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

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

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

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

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

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

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

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

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

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

Here’s how membership tests work in practice:

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

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

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

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

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

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

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

Here are some examples that compare tuples of integer values:

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

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

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

You can also compare tuples of different lengths:

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

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

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

Consider the following example:

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

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

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

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

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

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

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

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

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

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

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

Using Alternatives to the Built-in tuple Type

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Some more concrete use cases of tuples include the following:

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

Here are a few quick examples of these use cases:

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

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

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

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

In this tutorial, you’ve learned how to:

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

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

🐍 Python Tricks 💌

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

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

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

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

Aldren Santos

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

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

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

What Do You Think?

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

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

Keep Learning

Related Topics: intermediate python

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.

tuple' object does not support item assignment python

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List

Python Tuple

  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python tuple()

Python Tuple index()

Python Tuple count()

  • Python Lists Vs Tuples

Python del Statement

  • Python Dictionary items()

A tuple is a collection similar to a Python list . The primary difference is that we cannot modify a tuple once it is created.

  • Create a Python Tuple

We create a tuple by placing items inside parentheses () . For example,

More on Tuple Creation

We can also create a tuple using a tuple() constructor. For example,

Here are the different types of tuples we can create in Python.

Empty Tuple

Tuple of different data types

Tuple of mixed data types

Tuple Characteristics

Tuples are:

  • Ordered - They maintain the order of elements.
  • Immutable - They cannot be changed after creation.
  • Allow duplicates - They can contain duplicate values.
  • Access Tuple Items

Each item in a tuple is associated with a number, known as a index .

The index always starts from 0 , meaning the first item of a tuple is at index 0 , the second item is at index 1, and so on.

Index of Tuple Item

Access Items Using Index

We use index numbers to access tuple items. For example,

Access Tuple Items

Tuple Cannot be Modified

Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.

If we try to modify a tuple, we will get an error. For example,

  • Python Tuple Length

We use the len() function to find the number of items present in a tuple. For example,

  • Iterate Through a Tuple

We use the for loop to iterate over the items of a tuple. For example,

More on Python Tuple

We use the in keyword to check if an item exists in the tuple. For example,

  • yellow is not present in colors , so, 'yellow' in colors evaluates to False
  • red is present in colors , so, 'red' in colors evaluates to True

Python Tuples are immutable - we cannot change the items of a tuple once created.

If we try to do so, we will get an error. For example,

We cannot delete individual items of a tuple. However, we can delete the tuple itself using the del statement. For example,

Here, we have deleted the animals tuple.

When we want to create a tuple with a single item, we might do the following:

But this would not create a tuple; instead, it would be considered a string .

To solve this, we need to include a trailing comma after the item. For example,

  • Python Tuple Methods

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of Python tuple to the test! Can you solve the following challenge?

Write a function to modify a tuple by adding an element at the end of it.

  • For inputs with tuple (1, 2, 3) and element 4 , the return value should be (1, 2, 3, 4) .
  • Hint: You need to first convert the tuple to another data type, such as a list.

Video: Python Lists and Tuples

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Library

Python Tutorial

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

tuple' object does not support item assignment python

解决办法(两者取其一)

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

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

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

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

tuple' object does not support item assignment python

请填写红包祝福语或标题

tuple' object does not support item assignment python

ProblemTerminator

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

tuple' object does not support item assignment python

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

tuple' object does not support item assignment python

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

tuple' object does not support item assignment python

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

'TypeError: 'tuple' object does not support item assignment' when iterating through the rows of a layer

I'm trying to assign a value to the attributes of each feature of a feature layer. To do so I am just iterating through each row using 'arcpy.da.SearchCursor'.

However, I am getting the following error:

I really can't see what tuple is the error referring to. Besides, if I do the same thing but for just one feature (not iterating) I do not get the error and it works fine.

PolyGeo's user avatar

You appear to be trying to update values in your data using a Search Cursor arcpy.da.SearchCursor() rather than an Update Cursor arcpy.da.UpdateCursor()

Try changing to an Update Cursor:

Midavalo's user avatar

Your Answer

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 arcpy cursor arcgis-pro typeerror or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities

Hot Network Questions

  • Was Willy Wonka correct when he accused Charlie of stealing Fizzy Lifting Drinks?
  • Please help me identify my Dad's bike collection (80's-2000's)
  • Can flood basalt eruptions start in historical timescales?
  • Is this a misstatement of Euclid in Halmos' Naive Set Theory book?
  • Identify this 6 pin IC
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • Paying a parking fine when I don't trust the recipient
  • Navigating career options after a disastrous PhD performance and a disappointed advisor?
  • Engaging students in the beauty of mathematics
  • How to make conditions work in Which?
  • When should I put a biasing resistor - op-amps
  • Electrical panel not sending 240
  • 4/4 time change to 6/8 time
  • What's wrong with this solution?
  • How can I format a partition in a mapper device?
  • Book that features clones used for retirement
  • Why would the GPL be viral, while EUPL isn't, according to the EUPL authors?
  • Why are some Cloudflare challenges CPU intensive?
  • Is the white man at the other side of the Joliba river a historically identifiable person?
  • A probably Fantasy middle-length fiction about a probable vampire during the Blitz
  • What is the shortest viable hmac for non-critical applications?
  • Use of "them" in "…she fights for the rights and causes I believe need a warrior to champion them" by Taylor Swift
  • How to respond to subtle racism in the lab?
  • What would the natural diet of Bigfoot be?

tuple' object does not support item assignment python

  • python3 >

Pythonのタプル(tuple)の使い方・タプルの操作・例題について

記事内に広告が含まれています。

tuple' object does not support item assignment python

  • 2.1 インデックスによるアクセス
  • 2.4 要素のカウントと検索
  • 2.5 タプルのアンパック
  • 3.1 例題 1:要素の取得
  • 3.2 例題 2:要素の入れ替え
  • 3.3 例題 3:タプルの結合
  • 3.4 例題 4:要素が含まれているか確認

Pythonのタプル (tuple) は、順序付けられた 変更不可 のデータの集合を表すデータ型です。リスト (list) に似ていますが、タプルは一度作成すると要素を追加、削除、変更することができません。

タプルは丸括弧 () を使って作成します。複数の要素を持つタプルは、各要素をカンマ , で区切って定義します。

tuple' object does not support item assignment python

  • 順序性 : タプル内の要素は順序を持っており、インデックスを使って要素にアクセスできます。
  • 変更不可(イミュータブル) : タプルの要素を変更することはできません。一度作成したタプルの要素を追加、削除、変更することはできないため、タプルはリストに比べて安全です。

仮に要素を変更しようとすると次のようになります。

要素を変更したい場合は変数を更新することで、要素を更新することができます。

タプルには、リストと同様に多くの操作が可能です。以下にいくつかの基本操作を示します。

インデックスによるアクセス

tuple' object does not support item assignment python

  • count() : 指定した要素がタプル内に何回現れるかを返します。
  • index() : 指定した要素が最初に現れる位置(インデックス)を返します。

tuple' object does not support item assignment python

タプルの要素を個別の変数に展開( アンパック )することができます。

tuple' object does not support item assignment python

アンパックする際、変数の数はタプルの要素数と一致させる必要があります。また、 * を使うことで残りの要素をリストにまとめることも可能です。

tuple' object does not support item assignment python

  • my_tuple[0] で最初の要素を取得します。
  • my_tuple[-1] で最後の要素を取得します。
  • 両方の要素を新しいタプルにまとめます。

tuple' object does not support item assignment python

例題 2:要素の入れ替え

(1, 4, 3, 2, 5)

  • list() を使ってタプルをリストに変換します。
  • リストの2番目と4番目の要素を入れ替えます。
  • リストをタプルに戻します。

tuple' object does not support item assignment python

例題 3:タプルの結合

(1, 2, 3, 4)

  • タプル同士を + 演算子で結合します。

tuple' object does not support item assignment python

例題 4:要素が含まれているか確認

  • in 演算子を使って、タプルに 3 が含まれているか確認します。

tuple' object does not support item assignment python

  • Python »
  • 3.9.20 Documentation »
  • The Python Standard Library »
  • Generic Operating System Services »

os — Miscellaneous operating system interfaces ¶

Source code: Lib/os.py

This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open() , if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.

Notes on the availability of these functions:

The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function os.stat(path) returns stat information about path in the same format (which happens to have originated with the POSIX interface).

Extensions peculiar to a particular operating system are also available through the os module, but using them is of course a threat to portability.

All functions accepting path or file names accept both bytes and string objects, and result in an object of the same type, if a path or file name is returned.

On VxWorks, os.fork, os.execv and os.spawn*p* are not supported.

All functions in this module raise OSError (or subclasses thereof) in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

An alias for the built-in OSError exception.

The name of the operating system dependent module imported. The following names have currently been registered: 'posix' , 'nt' , 'java' .

Ayrıca bkz.

sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

File Names, Command Line Arguments, and Environment Variables ¶

In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the file system encoding to perform this conversion (see sys.getfilesystemencoding() ).

3.1 sürümünde değişti: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler , which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions may raise UnicodeErrors.

Process Parameters ¶

These functions and data items provide information and operate on the current process and user.

Return the filename corresponding to the controlling terminal of the process.

Availability : Unix.

A mapping object where keys and values are strings that represent the process environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py . Changes to the environment made after this time are not reflected in os.environ , except for changes made by modifying os.environ directly.

This mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

On Unix, keys and values use sys.getfilesystemencoding() and 'surrogateescape' error handler. Use environb if you would like to use a different encoding.

Calling putenv() directly does not change os.environ , so it’s better to modify os.environ .

On some platforms, including FreeBSD and macOS, setting environ may cause memory leaks. Refer to the system documentation for putenv() .

You can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ , and when one of the pop() or clear() methods is called.

3.9 sürümünde değişti: Updated to support PEP 584 ’s merge ( | ) and update ( |= ) operators.

Bytes version of environ : a mapping object where both keys and values are bytes objects representing the process environment. environ and environb are synchronized (modifying environb updates environ , and vice versa).

environb is only available if supports_bytes_environ is True .

3.2 sürümüyle geldi.

These functions are described in Files and Directories .

Encode path-like filename to the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return bytes unchanged.

fsdecode() is the reverse function.

3.6 sürümünde değişti: Support added to accept objects implementing the os.PathLike interface.

Decode the path-like filename from the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return str unchanged.

fsencode() is the reverse function.

Return the file system representation of the path.

If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__() is called and its value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised.

3.6 sürümüyle geldi.

An abstract base class for objects representing a file system path, e.g. pathlib.PurePath .

Return the file system path representation of the object.

The method should only return a str or bytes object, with the preference being for str .

Return the value of the environment variable key if it exists, or default if it doesn’t. key , default and the result are str. Note that since getenv() uses os.environ , the mapping of getenv() is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with sys.getfilesystemencoding() and 'surrogateescape' error handler. Use os.getenvb() if you would like to use a different encoding.

Availability : most flavors of Unix, Windows.

Return the value of the environment variable key if it exists, or default if it doesn’t. key , default and the result are bytes. Note that since getenvb() uses os.environb , the mapping of getenvb() is similarly also captured on import, and the function may not reflect future environment changes.

getenvb() is only available if supports_bytes_environ is True .

Availability : most flavors of Unix.

Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env , when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is None , environ is used.

Return the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process.

Return the current process’s effective user id.

Return the real group id of the current process.

Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user , because that group ID will otherwise be potentially omitted.

3.3 sürümüyle geldi.

Return list of supplemental group ids associated with the current process.

On macOS, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5 , getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups() , and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET , can be obtained with sysconfig.get_config_var() .

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.

Availability : Unix, Windows.

Return the process group id of the process with process id pid . If pid is 0, the process group id of the current process is returned.

Return the id of the current process group.

Return the current process id.

Return the parent’s process id. When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process.

3.2 sürümünde değişti: Added support for Windows.

Get program scheduling priority. The value which is one of PRIO_PROCESS , PRIO_PGRP , or PRIO_USER , and who is interpreted relative to which (a process identifier for PRIO_PROCESS , process group identifier for PRIO_PGRP , and a user ID for PRIO_USER ). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.

Parameters for the getpriority() and setpriority() functions.

Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids.

Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids.

Return the current process’s real user id.

Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.

Set the environment variable named key to the string value . Such changes to the environment affect subprocesses started with os.system() , popen() or fork() and execv() .

Assignments to items in os.environ are automatically translated into corresponding calls to putenv() ; however, calls to putenv() don’t update os.environ , so it is actually preferable to assign to items of os.environ . This also applies to getenv() and getenvb() , which respectively use os.environ and os.environb in their implementations.

Raises an auditing event os.putenv with arguments key , value .

3.9 sürümünde değişti: The function is now always available.

Set the current process’s effective group id.

Set the current process’s effective user id.

Set the current process’ group id.

Set the list of supplemental group ids associated with the current process to groups . groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.

On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().

Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

Call the system call setpgid() to set the process group id of the process with id pid to the process group with id pgrp . See the Unix manual for the semantics.

Set program scheduling priority. The value which is one of PRIO_PROCESS , PRIO_PGRP , or PRIO_USER , and who is interpreted relative to which (a process identifier for PRIO_PROCESS , process group identifier for PRIO_PGRP , and a user ID for PRIO_USER ). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. priority is a value in the range -20 to 19. The default priority is 0; lower priorities cause more favorable scheduling.

Set the current process’s real and effective group ids.

Set the current process’s real, effective, and saved group ids.

Set the current process’s real, effective, and saved user ids.

Set the current process’s real and effective user ids.

Call the system call getsid() . See the Unix manual for the semantics.

Call the system call setsid() . See the Unix manual for the semantics.

Set the current process’s user id.

Return the error message corresponding to the error code in code . On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.

True if the native OS type of the environment is bytes (eg. False on Windows).

Set the current numeric umask and return the previous umask.

Returns information identifying the current operating system. The return value is an object with five attributes:

sysname - operating system name

nodename - name of machine on network (implementation-defined)

release - operating system release

version - operating system version

machine - hardware identifier

For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname , nodename , release , version , and machine in that order.

Some systems truncate nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()) .

Availability : recent flavors of Unix.

3.3 sürümünde değişti: Return type changed from a tuple to a tuple-like object with named attributes.

Unset (delete) the environment variable named key . Such changes to the environment affect subprocesses started with os.system() , popen() or fork() and execv() .

Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv() ; however, calls to unsetenv() don’t update os.environ , so it is actually preferable to delete items of os.environ .

Raises an auditing event os.unsetenv with argument key .

3.9 sürümünde değişti: The function is now always available and is also available on Windows.

File Object Creation ¶

These functions create new file objects . (See also open() for opening file descriptors.)

Return an open file object connected to the file descriptor fd . This is an alias of the open() built-in function and accepts the same arguments. The only difference is that the first argument of fdopen() must always be an integer.

File Descriptor Operations ¶

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.

The fileno() method can be used to obtain the file descriptor associated with a file object when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.

Close file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To close a “file object” returned by the built-in function open() or by popen() or fdopen() , use its close() method.

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to (but much faster than):

Copy count bytes from file descriptor src , starting from offset offset_src , to file descriptor dst , starting from offset offset_dst . If offset_src is None, then src is read from the current position; respectively for offset_dst . The files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV .

This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary.

The return value is the amount of bytes copied. This could be less than the amount requested.

Availability : Linux kernel >= 4.5 or glibc >= 2.27.

3.8 sürümüyle geldi.

Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return None .

Return a duplicate of file descriptor fd . The new file descriptor is non-inheritable .

On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable .

3.4 sürümünde değişti: The new file descriptor is now non-inheritable.

Duplicate file descriptor fd to fd2 , closing the latter first if necessary. Return fd2 . The new file descriptor is inheritable by default or non-inheritable if inheritable is False .

3.4 sürümünde değişti: Add the optional inheritable parameter.

3.7 sürümünde değişti: Return fd2 on success. Previously, None was always returned.

Change the mode of the file given by fd to the numeric mode . See the docs for chmod() for possible values of mode . As of Python 3.3, this is equivalent to os.chmod(fd, mode) .

Raises an auditing event os.chmod with arguments path , mode , dir_fd .

Change the owner and group id of the file given by fd to the numeric uid and gid . To leave one of the ids unchanged, set it to -1. See chown() . As of Python 3.3, this is equivalent to os.chown(fd, uid, gid) .

Raises an auditing event os.chown with arguments path , uid , gid , dir_fd .

Force write of file with filedescriptor fd to disk. Does not force update of metadata.

This function is not available on MacOS.

Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in pathconf_names , an OSError is raised with errno.EINVAL for the error number.

As of Python 3.3, this is equivalent to os.pathconf(fd, name) .

Get the status of the file descriptor fd . Return a stat_result object.

As of Python 3.3, this is equivalent to os.stat(fd) .

The stat() function.

Return information about the filesystem containing the file associated with file descriptor fd , like statvfs() . As of Python 3.3, this is equivalent to os.statvfs(fd) .

Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.

If you’re starting with a buffered Python file object f , first do f.flush() , and then do os.fsync(f.fileno()) , to ensure that all internal buffers associated with f are written to disk.

Truncate the file corresponding to file descriptor fd , so that it is at most length bytes in size. As of Python 3.3, this is equivalent to os.truncate(fd, length) .

Raises an auditing event os.truncate with arguments fd , length .

3.5 sürümünde değişti: Added support for Windows

Get the blocking mode of the file descriptor: False if the O_NONBLOCK flag is set, True if the flag is cleared.

See also set_blocking() and socket.socket.setblocking() .

3.5 sürümüyle geldi.

Return True if the file descriptor fd is open and connected to a tty(-like) device, else False .

Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of F_LOCK , F_TLOCK , F_ULOCK or F_TEST . len specifies the section of the file to lock.

Raises an auditing event os.lockf with arguments fd , cmd , len .

Flags that specify what action lockf() will take.

Set the current position of file descriptor fd to position pos , modified by how : SEEK_SET or 0 to set the position relative to the beginning of the file; SEEK_CUR or 1 to set it relative to the current position; SEEK_END or 2 to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.

Parameters to the lseek() function. Their values are 0, 1, and 2, respectively.

3.3 sürümüyle geldi: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA .

Open the file path and set various flags according to flags and possibly its mode according to mode . When computing mode , the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable .

For a description of the flag and mode values, see the C run-time documentation; flag constants (like O_RDONLY and O_WRONLY ) are defined in the os module. In particular, on Windows adding O_BINARY is needed to open files in binary mode.

This function can support paths relative to directory descriptors with the dir_fd parameter.

Raises an auditing event open with arguments path , mode , flags .

This function is intended for low-level I/O. For normal usage, use the built-in function open() , which returns a file object with read() and write() methods (and many more). To wrap a file descriptor in a file object, use fdopen() .

3.3 sürümüyle geldi: The dir_fd argument.

3.5 sürümünde değişti: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

3.6 sürümünde değişti: Accepts a path-like object .

The following constants are options for the flags parameter to the open() function. They can be combined using the bitwise OR operator | . Some of them are not available on all platforms. For descriptions of their availability and use, consult the open(2) manual page on Unix or the MSDN on Windows.

The above constants are available on Unix and Windows.

The above constants are only available on Unix.

3.3 sürümünde değişti: Add O_CLOEXEC constant.

The above constants are only available on Windows.

The above constants are extensions and not present if they are not defined by the C library.

3.4 sürümünde değişti: Add O_PATH on systems that support it. Add O_TMPFILE , only available on Linux Kernel 3.11 or newer.

Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively. The new file descriptors are non-inheritable . For a (slightly) more portable approach, use the pty module.

Availability : some flavors of Unix.

3.4 sürümünde değişti: The new file descriptors are now non-inheritable.

Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. The new file descriptor is non-inheritable .

Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values: O_NONBLOCK , O_CLOEXEC . Return a pair of file descriptors (r, w) usable for reading and writing, respectively.

Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len bytes.

Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. advice is one of POSIX_FADV_NORMAL , POSIX_FADV_SEQUENTIAL , POSIX_FADV_RANDOM , POSIX_FADV_NOREUSE , POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED .

Flags that can be used in advice in posix_fadvise() that specify the access pattern that is likely to be used.

Read at most n bytes from file descriptor fd at a position of offset , leaving the file offset unchanged.

Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.

Read from a file descriptor fd at a position of offset into mutable bytes-like objects buffers , leaving the file offset unchanged. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.

The flags argument contains a bitwise OR of zero or more of the following flags:

Return the total number of bytes actually read which can be less than the total capacity of all the objects.

The operating system may set a limit ( sysconf() value 'SC_IOV_MAX' ) on the number of buffers that can be used.

Combine the functionality of os.readv() and os.pread() .

Availability : Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.6 or newer.

3.7 sürümüyle geldi.

Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock.

If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return -1 and set errno to errno.EAGAIN .

Availability : Linux 4.14 and newer.

High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources.

Currently, on Linux, this feature is usable only on a file descriptor opened using the O_DIRECT flag.

Availability : Linux 4.6 and newer.

Write the bytestring in str to file descriptor fd at position of offset , leaving the file offset unchanged.

Return the number of bytes actually written.

Write the buffers contents to file descriptor fd at a offset offset , leaving the file offset unchanged. buffers must be a sequence of bytes-like objects . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.

Return the total number of bytes actually written.

Combine the functionality of os.writev() and os.pwrite() .

Availability : Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.7 or newer.

Provide a per-write equivalent of the O_DSYNC open(2) flag. This flag effect applies only to the data range written by the system call.

Availability : Linux 4.7 and newer.

Provide a per-write equivalent of the O_SYNC open(2) flag. This flag effect applies only to the data range written by the system call.

Read at most n bytes from file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To read a “file object” returned by the built-in function open() or by popen() or fdopen() , or sys.stdin , use its read() or readline() methods.

Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset . Return the number of bytes sent. When EOF is reached return 0 .

The first function notation is supported by all platforms that define sendfile() .

On Linux, if offset is given as None , the bytes are read from the current position of in_fd and the position of in_fd is updated.

The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case.

On macOS and FreeBSD, a value of 0 for count specifies to send until the end of in_fd is reached.

All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.

Cross-platform applications should not use headers , trailers and flags arguments.

For a higher-level wrapper of sendfile() , see socket.socket.sendfile() .

3.9 sürümünde değişti: Parameters out and in was renamed to out_fd and in_fd .

Set the blocking mode of the specified file descriptor. Set the O_NONBLOCK flag if blocking is False , clear the flag otherwise.

See also get_blocking() and socket.socket.setblocking() .

Parameters to the sendfile() function, if the implementation supports them.

Read from a file descriptor fd into a number of mutable bytes-like objects buffers . Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.

Return the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ).

Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ) to pg .

Return a string which specifies the terminal device associated with file descriptor fd . If fd is not associated with a terminal device, an exception is raised.

Write the bytestring in str to file descriptor fd .

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe() . To write a “file object” returned by the built-in function open() or by popen() or fdopen() , or sys.stdout or sys.stderr , use its write() method.

Write the contents of buffers to file descriptor fd . buffers must be a sequence of bytes-like objects . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.

Returns the total number of bytes actually written.

Querying the size of a terminal ¶

Return the size of the terminal window as (columns, lines) , tuple of type terminal_size .

The optional argument fd (default STDOUT_FILENO , or standard output) specifies which file descriptor should be queried.

If the file descriptor is not connected to a terminal, an OSError is raised.

shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation.

A subclass of tuple, holding (columns, lines) of the terminal window size.

Width of the terminal window in characters.

Height of the terminal window in characters.

Inheritance of File Descriptors ¶

3.4 sürümüyle geldi.

A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.

On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.

On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout and stderr), which are always inherited. Using spawn* functions, all inheritable handles and all inheritable file descriptors are inherited. Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False .

Get the “inheritable” flag of the specified file descriptor (a boolean).

Set the “inheritable” flag of the specified file descriptor.

Get the “inheritable” flag of the specified handle (a boolean).

Availability : Windows.

Set the “inheritable” flag of the specified handle.

Files and Directories ¶

On some Unix platforms, many of these functions support one or more of these features:

specifying a file descriptor: Normally the path argument provided to functions in the os module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed with f (e.g. call fchdir instead of chdir ).)

You can check whether or not path can be specified as a file descriptor for a particular function on your platform using os.supports_fd . If this functionality is unavailable, using it will raise a NotImplementedError .

If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.

paths relative to directory descriptors: If dir_fd is not None , it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the variant of the function with an at suffix and possibly prefixed with f (e.g. call faccessat instead of access ).

You can check whether or not dir_fd is supported for a particular function on your platform using os.supports_dir_fd . If it’s unavailable, using it will raise a NotImplementedError .

not following symlinks: If follow_symlinks is False , and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.)

You can check whether or not follow_symlinks is supported for a particular function on your platform using os.supports_follow_symlinks . If it’s unavailable, using it will raise a NotImplementedError .

Use the real uid/gid to test for access to path . Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path . mode should be F_OK to test the existence of path , or it can be the inclusive OR of one or more of R_OK , W_OK , and X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) for more information.

This function can support specifying paths relative to directory descriptors and not following symlinks .

If effective_ids is True , access() will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available using os.supports_effective_ids . If it is unavailable, using it will raise a NotImplementedError .

Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

is better written as:

I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

3.3 sürümünde değişti: Added the dir_fd , effective_ids , and follow_symlinks parameters.

Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path , respectively.

Change the current working directory to path .

This function can support specifying a file descriptor . The descriptor must refer to an opened directory, not an open file.

This function can raise OSError and subclasses such as FileNotFoundError , PermissionError , and NotADirectoryError .

Raises an auditing event os.chdir with argument path .

3.3 sürümüyle geldi: Added support for specifying path as a file descriptor on some platforms.

Set the flags of path to the numeric flags . flags may take a combination (bitwise OR) of the following values (as defined in the stat module):

stat.UF_NODUMP

stat.UF_IMMUTABLE

stat.UF_APPEND

stat.UF_OPAQUE

stat.UF_NOUNLINK

stat.UF_COMPRESSED

stat.UF_HIDDEN

stat.SF_ARCHIVED

stat.SF_IMMUTABLE

stat.SF_APPEND

stat.SF_NOUNLINK

stat.SF_SNAPSHOT

This function can support not following symlinks .

Raises an auditing event os.chflags with arguments path , flags .

3.3 sürümüyle geldi: The follow_symlinks argument.

Change the mode of path to the numeric mode . mode may take one of the following values (as defined in the stat module) or bitwise ORed combinations of them:

stat.S_ISUID

stat.S_ISGID

stat.S_ENFMT

stat.S_ISVTX

stat.S_IREAD

stat.S_IWRITE

stat.S_IEXEC

stat.S_IRWXU

stat.S_IRUSR

stat.S_IWUSR

stat.S_IXUSR

stat.S_IRWXG

stat.S_IRGRP

stat.S_IWGRP

stat.S_IXGRP

stat.S_IRWXO

stat.S_IROTH

stat.S_IWOTH

stat.S_IXOTH

This function can support specifying a file descriptor , paths relative to directory descriptors and not following symlinks .

Although Windows supports chmod() , you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.

Change the owner and group id of path to the numeric uid and gid . To leave one of the ids unchanged, set it to -1.

See shutil.chown() for a higher-level function that accepts names in addition to numeric ids.

3.6 sürümünde değişti: Supports a path-like object .

Change the root directory of the current process to path .

Change the current working directory to the directory represented by the file descriptor fd . The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to os.chdir(fd) .

Return a string representing the current working directory.

Return a bytestring representing the current working directory.

3.8 sürümünde değişti: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.

Set the flags of path to the numeric flags , like chflags() , but do not follow symbolic links. As of Python 3.3, this is equivalent to os.chflags(path, flags, follow_symlinks=False) .

Change the mode of path to the numeric mode . If path is a symlink, this affects the symlink rather than the target. See the docs for chmod() for possible values of mode . As of Python 3.3, this is equivalent to os.chmod(path, mode, follow_symlinks=False) .

Change the owner and group id of path to the numeric uid and gid . This function will not follow symbolic links. As of Python 3.3, this is equivalent to os.chown(path, uid, gid, follow_symlinks=False) .

Create a hard link pointing to src named dst .

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors , and not following symlinks .

Raises an auditing event os.link with arguments src , dst , src_dir_fd , dst_dir_fd .

3.2 sürümünde değişti: Added Windows support.

3.3 sürümüyle geldi: Added the src_dir_fd , dst_dir_fd , and follow_symlinks arguments.

3.6 sürümünde değişti: Accepts a path-like object for src and dst .

Return a list containing the names of the entries in the directory given by path . The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

path may be a path-like object . If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes ; in all other circumstances, they will be of type str .

This function can also support specifying a file descriptor ; the file descriptor must refer to a directory.

Raises an auditing event os.listdir with argument path .

To encode str filenames to bytes , use fsencode() .

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

3.2 sürümünde değişti: The path parameter became optional.

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor.

Perform the equivalent of an lstat() system call on the given path. Similar to stat() , but does not follow symbolic links. Return a stat_result object.

On platforms that do not support symbolic links, this is an alias for stat() .

As of Python 3.3, this is equivalent to os.stat(path, dir_fd=dir_fd, follow_symlinks=False) .

This function can also support paths relative to directory descriptors .

3.2 sürümünde değişti: Added support for Windows 6.0 (Vista) symbolic links.

3.3 sürümünde değişti: Added the dir_fd parameter.

3.8 sürümünde değişti: On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for stat() .

Create a directory named path with numeric mode mode .

If the directory already exists, FileExistsError is raised. If a parent directory in the path does not exist, FileNotFoundError is raised.

On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode ) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call chmod() explicitly to set them.

On Windows, a mode of 0o700 is specifically handled to apply access control to the new directory such that only the current user and administrators have access. Other values of mode are ignored.

It is also possible to create temporary directories; see the tempfile module’s tempfile.mkdtemp() function.

Raises an auditing event os.mkdir with arguments path , mode , dir_fd .

3.9.20 sürümünde değişti: Windows now handles a mode of 0o700 .

Recursive directory creation function. Like mkdir() , but makes all intermediate-level directories needed to contain the leaf directory.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs() . The file permission bits of existing parent directories are not changed.

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.

makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems).

This function handles UNC paths correctly.

3.2 sürümüyle geldi: The exist_ok parameter.

3.4.1 sürümünde değişti: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082 .

3.7 sürümünde değişti: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.

Create a FIFO (a named pipe) named path with numeric mode mode . The current umask value is first masked out from the mode.

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink() ). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn’t open the FIFO — it just creates the rendezvous point.

Create a filesystem node (file, device special file or named pipe) named path . mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of stat.S_IFREG , stat.S_IFCHR , stat.S_IFBLK , and stat.S_IFIFO (those constants are available in stat ). For stat.S_IFCHR and stat.S_IFBLK , device defines the newly created device special file (probably using os.makedev() ), otherwise it is ignored.

Extract the device major number from a raw device number (usually the st_dev or st_rdev field from stat ).

Extract the device minor number from a raw device number (usually the st_dev or st_rdev field from stat ).

Compose a raw device number from the major and minor device numbers.

Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

This function can support specifying a file descriptor .

Dictionary mapping names accepted by pathconf() and fpathconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result) .

If the path is a string object (directly or indirectly through a PathLike interface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object (direct or indirectly), the result will be a bytes object.

When trying to resolve a path that may contain links, use realpath() to properly handle recursion and platform differences.

3.6 sürümünde değişti: Accepts a path-like object on Unix.

3.8 sürümünde değişti: Accepts a path-like object and a bytes object on Windows.

3.8 sürümünde değişti: Added support for directory junctions, and changed to return the substitution path (which typically includes \\?\ prefix) rather than the optional “print name” field that was previously returned.

Remove (delete) the file path . If path is a directory, an IsADirectoryError is raised. Use rmdir() to remove directories. If the file does not exist, a FileNotFoundError is raised.

This function can support paths relative to directory descriptors .

On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

This function is semantically identical to unlink() .

Raises an auditing event os.remove with arguments path , dir_fd .

Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz' , and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.

Rename the file or directory src to dst . If dst exists, the operation will fail with an OSError subclass in a number of cases:

On Windows, if dst exists a FileExistsError is always raised.

On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors .

If you want cross-platform overwriting of the destination, use replace() .

Raises an auditing event os.rename with arguments src , dst , src_dir_fd , dst_dir_fd .

3.3 sürümüyle geldi: The src_dir_fd and dst_dir_fd arguments.

Recursive directory or file renaming function. Works like rename() , except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs() .

This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.

3.6 sürümünde değişti: Accepts a path-like object for old and new .

Rename the file or directory src to dst . If dst is a non-empty directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

Remove (delete) the directory path . If the directory does not exist or is not empty, an FileNotFoundError or an OSError is raised respectively. In order to remove whole directory trees, shutil.rmtree() can be used.

Raises an auditing event os.rmdir with arguments path , dir_fd .

3.3 sürümüyle geldi: The dir_fd parameter.

Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path . The entries are yielded in arbitrary order, and the special entries '.' and '..' are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified.

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

path may be a path-like object . If path is of type bytes (directly or indirectly through the PathLike interface), the type of the name and path attributes of each os.DirEntry will be bytes ; in all other circumstances, they will be of type str .

Raises an auditing event os.scandir with argument path .

The scandir() iterator supports the context manager protocol and has the following method:

Close the iterator and free acquired resources.

This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the with statement.

The following example shows a simple use of scandir() to display all the files (excluding directories) in the given path that don’t start with '.' . The entry.is_file() call will generally not make an additional system call:

On Unix-based systems, scandir() uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions.

3.6 sürümüyle geldi: Added support for the context manager protocol and the close() method. If a scandir() iterator is neither exhausted nor explicitly closed a ResourceWarning will be emitted in its destructor.

The function accepts a path-like object .

3.7 sürümünde değişti: Added support for file descriptors on Unix.

Object yielded by scandir() to expose the file path and other file attributes of a directory entry.

scandir() will provide as much of this information as possible without making additional system calls. When a stat() or lstat() system call is made, the os.DirEntry object will cache the result.

os.DirEntry instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since calling scandir() , call os.stat(entry.path) to fetch up-to-date information.

Because the os.DirEntry methods can make operating system calls, they may also raise OSError . If you need very fine-grained control over errors, you can catch OSError when calling one of the os.DirEntry methods and handle as appropriate.

To be directly usable as a path-like object , os.DirEntry implements the PathLike interface.

Attributes and methods on a os.DirEntry instance are as follows:

The entry’s base filename, relative to the scandir() path argument.

The name attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.

The entry’s full path name: equivalent to os.path.join(scandir_path, entry.name) where scandir_path is the scandir() path argument. The path is only absolute if the scandir() path argument was absolute. If the scandir() path argument was a file descriptor , the path attribute is the same as the name attribute.

The path attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.

Return the inode number of the entry.

The result is cached on the os.DirEntry object. Use os.stat(entry.path, follow_symlinks=False).st_ino to fetch up-to-date information.

On the first, uncached call, a system call is required on Windows but not on Unix.

Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore.

If follow_symlinks is False , return True only if this entry is a directory (without following symlinks); return False if the entry is any other kind of file or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False . Call os.stat() along with stat.S_ISDIR() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN . If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks is False .

This method can raise OSError , such as PermissionError , but FileNotFoundError is caught and not raised.

Return True if this entry is a file or a symbolic link pointing to a file; return False if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore.

If follow_symlinks is False , return True only if this entry is a file (without following symlinks); return False if the entry is a directory or other non-file entry, or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Caching, system calls made, and exceptions raised are as per is_dir() .

Return True if this entry is a symbolic link (even if broken); return False if the entry points to a directory or any kind of file, or if it doesn’t exist anymore.

The result is cached on the os.DirEntry object. Call os.path.islink() to fetch up-to-date information.

On the first, uncached call, no system call is required in most cases. Specifically, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN .

Return a stat_result object for this entry. This method follows symbolic links by default; to stat a symbolic link add the follow_symlinks=False argument.

On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is True and the entry is a reparse point (for example, a symbolic link or directory junction).

On Windows, the st_ino , st_dev and st_nlink attributes of the stat_result are always set to zero. Call os.stat() to get these attributes.

The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False . Call os.stat() to fetch up-to-date information.

Note that there is a nice correspondence between several attributes and methods of os.DirEntry and of pathlib.Path . In particular, the name attribute has the same meaning, as do the is_dir() , is_file() , is_symlink() and stat() methods.

3.6 sürümünde değişti: Added support for the PathLike interface. Added support for bytes paths on Windows.

Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object.

This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False , or use lstat() .

This function can support specifying a file descriptor and not following symlinks .

On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions.

fstat() and lstat() functions.

3.3 sürümüyle geldi: Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path.

3.8 sürümünde değişti: On Windows, all reparse points that can be resolved by the operating system are now followed, and passing follow_symlinks=False disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns the information for the original path as if follow_symlinks=False had been specified instead of raising an error.

Object whose attributes correspond roughly to the members of the stat structure. It is used for the result of os.stat() , os.fstat() and os.lstat() .

Attributes:

File mode: file type and file mode bits (permissions).

Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev . Typically:

the inode number on Unix,

the file index on Windows

Identifier of the device on which this file resides.

Number of hard links.

User identifier of the file owner.

Group identifier of the file owner.

Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.

Timestamps:

Time of most recent access expressed in seconds.

Time of most recent content modification expressed in seconds.

Platform dependent:

the time of most recent metadata change on Unix,

the time of creation on Windows, expressed in seconds.

Time of most recent access expressed in nanoseconds as an integer.

Time of most recent content modification expressed in nanoseconds as an integer.

the time of creation on Windows, expressed in nanoseconds as an integer.

The exact meaning and resolution of the st_atime , st_mtime , and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details.

Similarly, although st_atime_ns , st_mtime_ns , and st_ctime_ns are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store st_atime , st_mtime , and st_ctime cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use st_atime_ns , st_mtime_ns , and st_ctime_ns .

On some Unix systems (such as Linux), the following attributes may also be available:

Number of 512-byte blocks allocated for file. This may be smaller than st_size /512 when the file has holes.

“Preferred” blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.

Type of device if an inode device.

User defined flags for file.

On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them):

File generation number.

Time of file creation.

On Solaris and derivatives, the following attributes may also be available:

String that uniquely identifies the type of the filesystem that contains the file.

On macOS systems, the following attributes may also be available:

Real size of the file.

Creator of the file.

On Windows systems, the following attributes are also available:

Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle() . See the FILE_ATTRIBUTE_* constants in the stat module.

When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module.

The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.)

For backward compatibility, a stat_result instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode , st_ino , st_dev , st_nlink , st_uid , st_gid , st_size , st_atime , st_mtime , st_ctime . More items may be added at the end by some implementations. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers.

3.3 sürümüyle geldi: Added the st_atime_ns , st_mtime_ns , and st_ctime_ns members.

3.5 sürümüyle geldi: Added the st_file_attributes member on Windows.

3.5 sürümünde değişti: Windows now returns the file index as st_ino when available.

3.7 sürümüyle geldi: Added the st_fstype member to Solaris/derivatives.

3.8 sürümüyle geldi: Added the st_reparse_tag member on Windows.

3.8 sürümünde değişti: On Windows, the st_mode member now identifies special files as S_IFCHR , S_IFIFO or S_IFBLK as appropriate.

Perform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize , f_frsize , f_blocks , f_bfree , f_bavail , f_files , f_ffree , f_favail , f_flag , f_namemax , f_fsid .

Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported.

Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime/ctime).

3.2 sürümünde değişti: The ST_RDONLY and ST_NOSUID constants were added.

3.4 sürümünde değişti: The ST_NODEV , ST_NOEXEC , ST_SYNCHRONOUS , ST_MANDLOCK , ST_WRITE , ST_APPEND , ST_IMMUTABLE , ST_NOATIME , ST_NODIRATIME , and ST_RELATIME constants were added.

3.7 sürümüyle geldi: Added f_fsid .

A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.)

To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd . As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform:

Currently dir_fd parameters only work on Unix platforms; none of them work on Windows.

A set object indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform. (Specifying False for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will contain os.access() ; otherwise it will be empty.

This expression evaluates to True if os.access() supports effective_ids=True on the local platform:

Currently effective_ids is only supported on Unix platforms; it does not work on Windows.

A set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports.

To determine whether a particular function permits specifying an open file descriptor for its path parameter, use the in operator on supports_fd . As an example, this expression evaluates to True if os.chdir() accepts open file descriptors for path on your local platform:

A set object indicating which functions in the os module accept False for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying True for follow_symlinks is always supported on all platforms.)

To check whether a particular function accepts False for its follow_symlinks parameter, use the in operator on supports_follow_symlinks . As an example, this expression evaluates to True if you may specify follow_symlinks=False when calling os.stat() on the local platform:

Create a symbolic link pointing to src named dst .

On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored.

On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator.

OSError is raised when the function is called by an unprivileged user.

Raises an auditing event os.symlink with arguments src , dst , dir_fd .

3.3 sürümüyle geldi: Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms.

3.8 sürümünde değişti: Added support for unelevated symlinks on Windows with Developer Mode.

Force write of everything to disk.

Truncate the file corresponding to path , so that it is at most length bytes in size.

Raises an auditing event os.truncate with arguments path , length .

Remove (delete) the file path . This function is semantically identical to remove() ; the unlink name is its traditional Unix name. Please see the documentation for remove() for further information.

Set the access and modified times of the file specified by path .

utime() takes two optional parameters, times and ns . These specify the times set on path and are used as follows:

If ns is specified, it must be a 2-tuple of the form (atime_ns, mtime_ns) where each member is an int expressing nanoseconds.

If times is not None , it must be a 2-tuple of the form (atime, mtime) where each member is an int or float expressing seconds.

If times is None and ns is unspecified, this is equivalent to specifying ns=(atime_ns, mtime_ns) where both times are the current time.

It is an error to specify tuples for both times and ns .

Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat() . The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime .

Raises an auditing event os.utime with arguments path , times , ns , dir_fd .

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor, and the dir_fd , follow_symlinks , and ns parameters.

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames) .

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..' ). filenames is a list of the names of the non-directory files in dirpath . Note that the names in the lists contain no path components. To get a full path (which begins with top ) to a file or directory in dirpath , do os.path.join(dirpath, name) . Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.

If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False , the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown , the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

When topdown is True , the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames ; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

By default, errors from the scandir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object.

By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

If you pass a relative pathname, don’t change the current working directory between resumptions of walk() . walk() never changes the current directory, and assumes that its caller doesn’t either.

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

In the next example (simple implementation of shutil.rmtree() ), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty:

Raises an auditing event os.walk with arguments top , topdown , onerror , followlinks .

3.5 sürümünde değişti: This function now calls os.scandir() instead of os.listdir() , making it faster by reducing the number of calls to os.stat() .

This behaves exactly like walk() , except that it yields a 4-tuple (dirpath, dirnames, filenames, dirfd) , and it supports dir_fd .

dirpath , dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath .

This function always supports paths relative to directory descriptors and not following symlinks . Note however that, unlike other functions, the fwalk() default value for follow_symlinks is False .

Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with dup() ) if you want to keep them longer.

In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty:

Raises an auditing event os.fwalk with arguments top , topdown , onerror , follow_symlinks , dir_fd .

3.7 sürümünde değişti: Added support for bytes paths.

Create an anonymous file and return a file descriptor that refers to it. flags must be one of the os.MFD_* constants available on the system (or a bitwise ORed combination of them). By default, the new file descriptor is non-inheritable .

The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory /proc/self/fd/ . The displayed name is always prefixed with memfd: and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects.

Availability : Linux 3.17 or newer with glibc 2.27 or newer.

These flags can be passed to memfd_create() .

Availability : Linux 3.17 or newer with glibc 2.27 or newer. The MFD_HUGE* flags are only available since Linux 4.14.

Linux extended attributes ¶

These functions are all available on Linux only.

Return the value of the extended filesystem attribute attribute for path . attribute can be bytes or str (directly or indirectly through the PathLike interface). If it is str, it is encoded with the filesystem encoding.

Raises an auditing event os.getxattr with arguments path , attribute .

3.6 sürümünde değişti: Accepts a path-like object for path and attribute .

Return a list of the extended filesystem attributes on path . The attributes in the list are represented as strings decoded with the filesystem encoding. If path is None , listxattr() will examine the current directory.

Raises an auditing event os.listxattr with argument path .

Removes the extended filesystem attribute attribute from path . attribute should be bytes or str (directly or indirectly through the PathLike interface). If it is a string, it is encoded with the filesystem encoding.

Raises an auditing event os.removexattr with arguments path , attribute .

Set the extended filesystem attribute attribute on path to value . attribute must be a bytes or str with no embedded NULs (directly or indirectly through the PathLike interface). If it is a str, it is encoded with the filesystem encoding. flags may be XATTR_REPLACE or XATTR_CREATE . If XATTR_REPLACE is given and the attribute does not exist, ENODATA will be raised. If XATTR_CREATE is given and the attribute already exists, the attribute will not be created and EEXISTS will be raised.

A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.

Raises an auditing event os.setxattr with arguments path , attribute , value , flags .

The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.

This is a possible value for the flags argument in setxattr() . It indicates the operation must create an attribute.

This is a possible value for the flags argument in setxattr() . It indicates the operation must replace an existing attribute.

Process Management ¶

These functions may be used to create and manage processes.

The various exec* functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program’s main() . For example, os.execv('/bin/echo', ['foo', 'bar']) will only print bar on standard output; foo will seem to be ignored.

Generate a SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of 3 . Be aware that calling this function will not call the Python signal handler registered for SIGABRT with signal.signal() .

Add a path to the DLL search path.

This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path ), and also by ctypes .

Remove the directory by calling close() on the returned object or using it in a with statement.

See the Microsoft documentation for more information about how DLLs are loaded.

Raises an auditing event os.add_dll_directory with argument path .

3.8 sürümüyle geldi: Previous versions of CPython would resolve DLLs using the default behavior for the current process. This led to inconsistencies, such as only sometimes searching PATH or the current working directory, and OS functions such as AddDllDirectory having no effect.

In 3.8, the two primary ways DLLs are loaded now explicitly override the process-wide behavior to ensure consistency. See the porting notes for information on updating libraries.

These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec* function.

The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.

The variants which include a “p” near the end ( execlp() , execlpe() , execvp() , and execvpe() ) will use the PATH environment variable to locate the program file . When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl() , execle() , execv() , and execve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For execle() , execlpe() , execve() , and execvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions execl() , execlp() , execv() , and execvp() all cause the new process to inherit the environment of the current process.

For execve() on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using os.supports_fd . If it is unavailable, using it will raise a NotImplementedError .

Raises an auditing event os.exec with arguments path , args , env .

3.3 sürümüyle geldi: Added support for specifying path as an open file descriptor for execve() .

Exit the process with status n , without calling cleanup handlers, flushing stdio buffers, etc.

The standard way to exit is sys.exit(n) . _exit() should normally only be used in the child process after a fork() .

The following exit codes are defined and can be used with _exit() , although they are not required. These are typically used for system programs written in Python, such as a mail server’s external command delivery program.

Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.

Exit code that means no error occurred.

Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.

Exit code that means the input data was incorrect.

Exit code that means an input file did not exist or was not readable.

Exit code that means a specified user did not exist.

Exit code that means a specified host did not exist.

Exit code that means that a required service is unavailable.

Exit code that means an internal software error was detected.

Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.

Exit code that means some system file did not exist, could not be opened, or had some other kind of error.

Exit code that means a user specified output file could not be created.

Exit code that means that an error occurred while doing I/O on some file.

Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation.

Exit code that means that a protocol exchange was illegal, invalid, or not understood.

Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).

Exit code that means that some kind of configuration error occurred.

Exit code that means something like “an entry was not found”.

Fork a child process. Return 0 in the child and the child’s process id in the parent. If an error occurs OSError is raised.

Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread.

Raises an auditing event os.fork with no arguments.

3.8 sürümünde değişti: Calling fork() in a subinterpreter is no longer supported ( RuntimeError is raised).

See ssl for applications that use the SSL module with fork().

Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of (pid, fd) , where pid is 0 in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the pty module. If an error occurs OSError is raised.

Raises an auditing event os.forkpty with no arguments.

3.8 sürümünde değişti: Calling forkpty() in a subinterpreter is no longer supported ( RuntimeError is raised).

Send signal sig to the process pid . Constants for the specific signals available on the host platform are defined in the signal module.

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig . The Windows version of kill() additionally takes process handles to be killed.

See also signal.pthread_kill() .

Raises an auditing event os.kill with arguments pid , sig .

3.2 sürümüyle geldi: Windows support.

Send the signal sig to the process group pgid .

Raises an auditing event os.killpg with arguments pgid , sig .

Add increment to the process’s “niceness”. Return the new niceness.

Return a file descriptor referring to the process pid . This descriptor can be used to perform process management without races and signals. The flags argument is provided for future extensions; no flag values are currently defined.

See the pidfd_open(2) man page for more details.

Availability : Linux 5.3+

3.9 sürümüyle geldi.

Lock program segments into memory. The value of op (defined in <sys/lock.h> ) determines which segments are locked.

Open a pipe to or from command cmd . The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w' . The buffering argument has the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes.

The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be - signal.SIGKILL if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.

On Unix, waitstatus_to_exitcode() can be used to convert the close method result (exit status) into an exit code if it is not None . On Windows, the close method result is directly the exit code (or None ).

This is implemented using subprocess.Popen ; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.

Wraps the posix_spawn() C library API for use from Python.

Most users should use subprocess.run() instead of posix_spawn() .

The positional-only arguments path , args , and env are similar to execve() .

The path parameter is the path to the executable file. The path should contain a directory. Use posix_spawnp() to pass an executable file without directory.

The file_actions argument may be a sequence of tuples describing actions to take on specific file descriptors in the child process between the C library implementation’s fork() and exec() steps. The first item in each tuple must be one of the three type indicator listed below describing the remaining tuple elements:

( os.POSIX_SPAWN_OPEN , fd , path , flags , mode )

Performs os.dup2(os.open(path, flags, mode), fd) .

( os.POSIX_SPAWN_CLOSE , fd )

Performs os.close(fd) .

( os.POSIX_SPAWN_DUP2 , fd , new_fd )

Performs os.dup2(fd, new_fd) .

These tuples correspond to the C library posix_spawn_file_actions_addopen() , posix_spawn_file_actions_addclose() , and posix_spawn_file_actions_adddup2() API calls used to prepare for the posix_spawn() call itself.

The setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library POSIX_SPAWN_SETPGROUP flag.

If the resetids argument is True it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument is False , then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C library POSIX_SPAWN_RESETIDS flag.

If the setsid argument is True , it will create a new session ID for posix_spawn . setsid requires POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedError is raised.

The setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library POSIX_SPAWN_SETSIGMASK flag.

The sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library POSIX_SPAWN_SETSIGDEF flag.

The scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of sched_param with the scheduler parameters. A value of None in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C library POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULER flags.

Raises an auditing event os.posix_spawn with arguments path , argv , env .

Wraps the posix_spawnp() C library API for use from Python.

Similar to posix_spawn() except that the system searches for the executable file in the list of directories specified by the PATH environment variable (in the same way as for execvp(3) ).

Availability : See posix_spawn() documentation.

Register callables to be executed when a new child process is forked using os.fork() or similar process cloning APIs. The parameters are optional and keyword-only. Each specifies a different call point.

before is a function called before forking a child process.

after_in_parent is a function called from the parent process after forking a child process.

after_in_child is a function called from the child process.

These calls are only made if control is expected to return to the Python interpreter. A typical subprocess launch will not trigger them as the child is not going to re-enter the interpreter.

Functions registered for execution before forking are called in reverse registration order. Functions registered for execution after forking (either in the parent or in the child) are called in registration order.

Note that fork() calls made by third-party C code may not call those functions, unless it explicitly calls PyOS_BeforeFork() , PyOS_AfterFork_Parent() and PyOS_AfterFork_Child() .

There is no way to unregister a function.

Execute the program path in a new process.

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.)

If mode is P_NOWAIT , this function returns the process id of the new process; if mode is P_WAIT , returns the process’s exit code if it exits normally, or -signal , where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function.

Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception.

The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run.

The variants which include a second “p” near the end ( spawnlp() , spawnlpe() , spawnvp() , and spawnvpe() ) will use the PATH environment variable to locate the program file . When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl() , spawnle() , spawnv() , and spawnve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For spawnle() , spawnlpe() , spawnve() , and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl() , spawnlp() , spawnv() , and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127 .

As an example, the following calls to spawnlp() and spawnvpe() are equivalent:

Raises an auditing event os.spawn with arguments mode , path , args , env .

Availability : Unix, Windows. spawnlp() , spawnlpe() , spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead.

Possible values for the mode parameter to the spawn* family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process id as the return value.

Possible value for the mode parameter to the spawn* family of functions. If this is given as mode , the spawn*() functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or -signal if a signal kills the process.

Possible values for the mode parameter to the spawn* family of functions. These are less portable than those listed above. P_DETACH is similar to P_NOWAIT , but the new process is detached from the console of the calling process. If P_OVERLAY is used, the current process will be replaced; the spawn* function will not return.

Start a file with its associated application.

When operation is not specified or 'open' , this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories).

startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash ( '/' ); the underlying Win32 ShellExecute() function doesn’t work if it is. Use the os.path.normpath() function to ensure that the path is properly encoded for Win32.

To reduce interpreter startup overhead, the Win32 ShellExecute() function is not resolved until this function is first called. If the function cannot be resolved, NotImplementedError will be raised.

Raises an auditing event os.startfile with arguments path , operation .

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system() , and has the same limitations. Changes to sys.stdin , etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for wait() .

On Windows, the return value is that returned by the system shell after running command . The shell is given by the Windows environment variable COMSPEC : it is usually cmd.exe , which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

On Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code.

Raises an auditing event os.system with argument command .

Returns the current global process times. The return value is an object with five attributes:

user - user time

system - system time

children_user - user time of all child processes

children_system - system time of all child processes

elapsed - elapsed real time since a fixed point in the past

For backwards compatibility, this object also behaves like a five-tuple containing user , system , children_user , children_system , and elapsed in that order.

See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero.

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

waitstatus_to_exitcode() can be used to convert the exit status into an exit code.

waitpid() can be used to wait for the completion of a specific child process and has more options.

Wait for the completion of one or more child processes. idtype can be P_PID , P_PGID , P_ALL , or P_PIDFD on Linux. id specifies the pid to wait on. options is constructed from the ORing of one or more of WEXITED , WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT . The return value is an object representing the data contained in the siginfo_t structure, namely: si_pid , si_uid , si_signo , si_status , si_code or None if WNOHANG is specified and there are no children in a waitable state.

These are the possible values for idtype in waitid() . They affect how id is interpreted.

This is a Linux-specific idtype that indicates that id is a file descriptor that refers to a process.

Availability : Linux 5.4+

Flags that can be used in options in waitid() that specify what child signal to wait for.

These are the possible values for si_code in the result returned by waitid() .

3.9 sürümünde değişti: Added CLD_KILLED and CLD_STOPPED values.

The details of this function differ on Unix and Windows.

On Unix: Wait for completion of a child process given by process id pid , and return a tuple containing its process id and exit status indication (encoded as for wait() ). The semantics of the call are affected by the value of the integer options , which should be 0 for normal operation.

If pid is greater than 0 , waitpid() requests status information for that specific process. If pid is 0 , the request is for the status of any child in the process group of the current process. If pid is -1 , the request pertains to any child of the current process. If pid is less than -1 , status is requested for any process in the process group -pid (the absolute value of pid ).

An OSError is raised with the value of errno when the syscall returns -1.

On Windows: Wait for completion of a process given by process handle pid , and return a tuple containing pid , and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to 0 has no special meaning on Windows, and raises an exception. The value of integer options has no effect. pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles.

Similar to waitpid() , except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource . getrusage() for details on resource usage information. The option argument is the same as that provided to waitpid() and wait4() .

waitstatus_to_exitcode() can be used to convert the exit status into an exitcode.

Similar to waitpid() , except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource . getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid() .

Convert a wait status to an exit code.

If the process exited normally (if WIFEXITED(status) is true), return the process exit status (return WEXITSTATUS(status) ): result greater than or equal to 0.

If the process was terminated by a signal (if WIFSIGNALED(status) is true), return -signum where signum is the number of the signal that caused the process to terminate (return -WTERMSIG(status) ): result less than 0.

Otherwise, raise a ValueError .

On Windows, return status shifted right by 8 bits.

On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) is true.

WIFEXITED() , WEXITSTATUS() , WIFSIGNALED() , WTERMSIG() , WIFSTOPPED() , WSTOPSIG() functions.

The option for waitpid() to return immediately if no child process status is available immediately. The function returns (0, 0) in this case.

This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.

Availability : some Unix systems.

This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.

The following functions take a process status code as returned by system() , wait() , or waitpid() as a parameter. They may be used to determine the disposition of a process.

Return True if a core dump was generated for the process, otherwise return False .

This function should be employed only if WIFSIGNALED() is true.

Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False .

See WCONTINUED option.

Return True if the process was stopped by delivery of a signal, otherwise return False .

WIFSTOPPED() only returns True if the waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2) ).

Return True if the process was terminated by a signal, otherwise return False .

Return True if the process exited terminated normally, that is, by calling exit() or _exit() , or by returning from main() ; otherwise return False .

Return the process exit status.

This function should be employed only if WIFEXITED() is true.

Return the signal which caused the process to stop.

This function should be employed only if WIFSTOPPED() is true.

Return the number of the signal that caused the process to terminate.

Interface to the scheduler ¶

These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix manpages.

The following scheduling policies are exposed if they are supported by the operating system.

The default scheduling policy.

Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.

Scheduling policy for extremely low priority background tasks.

Scheduling policy for sporadic server programs.

A First In First Out scheduling policy.

A round-robin scheduling policy.

This flag can be OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.

This class represents tunable scheduling parameters used in sched_setparam() , sched_setscheduler() , and sched_getparam() . It is immutable.

At the moment, there is only one possible parameter:

The scheduling priority for a scheduling policy.

Get the minimum priority value for policy . policy is one of the scheduling policy constants above.

Get the maximum priority value for policy . policy is one of the scheduling policy constants above.

Set the scheduling policy for the process with PID pid . A pid of 0 means the calling process. policy is one of the scheduling policy constants above. param is a sched_param instance.

Return the scheduling policy for the process with PID pid . A pid of 0 means the calling process. The result is one of the scheduling policy constants above.

Set the scheduling parameters for the process with PID pid . A pid of 0 means the calling process. param is a sched_param instance.

Return the scheduling parameters as a sched_param instance for the process with PID pid . A pid of 0 means the calling process.

Return the round-robin quantum in seconds for the process with PID pid . A pid of 0 means the calling process.

Voluntarily relinquish the CPU.

Restrict the process with PID pid (or the current process if zero) to a set of CPUs. mask is an iterable of integers representing the set of CPUs to which the process should be restricted.

Return the set of CPUs the process with PID pid (or the current process if zero) is restricted to.

Miscellaneous System Information ¶

Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the confstr_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

If the configuration value specified by name isn’t defined, None is returned.

If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in confstr_names , an OSError is raised with errno.EINVAL for the error number.

Dictionary mapping names accepted by confstr() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

Return the number of CPUs in the system. Returns None if undetermined.

This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0))

Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises OSError if the load average was unobtainable.

Return integer-valued system configuration values. If the configuration value specified by name isn’t defined, -1 is returned. The comments regarding the name parameter for confstr() apply here as well; the dictionary that provides information on the known names is given by sysconf_names .

Dictionary mapping names accepted by sysconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

The following data values are used to support path manipulation operations. These are defined for all platforms.

Higher-level operations on pathnames are defined in the os.path module.

The constant string used by the operating system to refer to the current directory. This is '.' for Windows and POSIX. Also available via os.path .

The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path .

The character used by the operating system to separate pathname components. This is '/' for POSIX and '\\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os.path.split() and os.path.join() — but it is occasionally useful. Also available via os.path .

An alternative character used by the operating system to separate pathname components, or None if only one separator character exists. This is set to '/' on Windows systems where sep is a backslash. Also available via os.path .

The character which separates the base filename from the extension; for example, the '.' in os.py . Also available via os.path .

The character conventionally used by the operating system to separate search path components (as in PATH ), such as ':' for POSIX or ';' for Windows. Also available via os.path .

The default search path used by exec*p* and spawn*p* if the environment doesn’t have a 'PATH' key. Also available via os.path .

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

The file path of the null device. For example: '/dev/null' for POSIX, 'nul' for Windows. Also available via os.path .

Flags for use with the setdlopenflags() and getdlopenflags() functions. See the Unix manual page dlopen(3) for what the different flags mean.

Random numbers ¶

Get up to size random bytes. The function can return less bytes than requested.

These bytes can be used to seed user-space random number generators or for cryptographic purposes.

getrandom() relies on entropy gathered from device drivers and other sources of environmental noise. Unnecessarily reading large quantities of data will have a negative impact on other users of the /dev/random and /dev/urandom devices.

The flags argument is a bit mask that can contain zero or more of the following values ORed together: os.GRND_RANDOM and GRND_NONBLOCK .

See also the Linux getrandom() manual page .

Availability : Linux 3.17 and newer.

Return a bytestring of size random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.

On Linux, if the getrandom() syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale. On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized.

On a Unix-like system, random bytes are read from the /dev/urandom device. If the /dev/urandom device is not available or not readable, the NotImplementedError exception is raised.

On Windows, it will use CryptGenRandom() .

The secrets module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom .

3.6.0 sürümünde değişti: On Linux, getrandom() is now used in blocking mode to increase the security.

3.5.2 sürümünde değişti: On Linux, if the getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom .

3.5 sürümünde değişti: On Linux 3.17 and newer, the getrandom() syscall is now used when available. On OpenBSD 5.6 and newer, the C getentropy() function is now used. These functions avoid the usage of an internal file descriptor.

By default, when reading from /dev/random , getrandom() blocks if no random bytes are available, and when reading from /dev/urandom , it blocks if the entropy pool has not yet been initialized.

If the GRND_NONBLOCK flag is set, then getrandom() does not block in these cases, but instead immediately raises BlockingIOError .

If this bit is set, then random bytes are drawn from the /dev/random pool instead of the /dev/urandom pool.

Table of Contents

  • File Names, Command Line Arguments, and Environment Variables
  • Process Parameters
  • File Object Creation
  • Querying the size of a terminal
  • Inheritance of File Descriptors
  • Linux extended attributes
  • Process Management
  • Interface to the scheduler
  • Miscellaneous System Information
  • Random numbers

Önceki konu

Generic Operating System Services

Sonraki konu

io — Core tools for working with streams

  • Hata Bildir
  • Kaynağı Göster
  • 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.

Type error when accessing a Protobuf map in Python

I get the "TypeError: RepeatedCompositeFieldContainer object does not support item assignment" when accessing the Protobuf map in Python

Proto definition:

Accessing from Python:

The error message I get is:

Protobuf version: 4.25.1

What could be the issue? Thanks

  • protocol-buffers

veda's user avatar

  • Using protoc version v28 or version 3.19.6 -- with Python 3.12 -- I cannot reproduce this behavior. test.myMap["key"] = "value" runs without errors (and I can subsequently access test.myMap["key"] and retrieve the expected value). –  larsks Commented yesterday

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged python protocol-buffers or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Why do "modern" languages not provide argv and exit code in main?
  • When does a finite group have finitely many indecomposable representations?
  • How do I go about writing a tragic ending in a story while making it overall satisfying to the reader?
  • Electrical panel not sending 240
  • When should I put a biasing resistor - op-amps
  • What would the natural diet of Bigfoot be?
  • What is a natural-sounding verb form for the word dorveille?
  • Book that features clones used for retirement
  • Please help me identify my Dad's bike collection (80's-2000's)
  • Should I write an email to a Latino teacher working in the US in English or Spanish?
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • How can a microcontroller (such as an Arduino Uno) that requires 7-21V input voltage be powered via USB-B which can only run 5V?
  • Big Transition of Binary Counting in perspective of IEEE754 floating point
  • What's wrong with this solution?
  • How to prove that the Greek cross tiles the plane?
  • Engaging students in the beauty of mathematics
  • Is the closest diagonal state to a given state always the dephased original state?
  • 4/4 time change to 6/8 time
  • Is this a misstatement of Euclid in Halmos' Naive Set Theory book?
  • Maximize finds solution outside the constraint
  • How to make conditions work in Which?
  • What prevents indoor climbing gyms from making a v18 boulder even if one hasn't been found outside?
  • Is it feasible to create an online platform to effectively teach college-level math (abstract algebra, real analysis, etc.)?
  • What is the rationale behind 32333 "Technic Pin Connector Block 1 x 5 x 3"?

tuple' object does not support item assignment python

IMAGES

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

    tuple' object does not support item assignment python

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

    tuple' object does not support item assignment python

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

    tuple' object does not support item assignment python

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

    tuple' object does not support item assignment python

  5. TypeError: ‘tuple’ object does not support item assignment

    tuple' object does not support item assignment python

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

    tuple' object does not support item assignment python

VIDEO

  1. tuple syntax doesn't have parens (beginner

  2. What does n-tuple mean?

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

  4. 15- append item to a tuple in python

  5. multiple assignment in python

  6. I Learned Something New About Tuples In Python 3.11

COMMENTS

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

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

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

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

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

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

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

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

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

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

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

  9. Tuple Error In Python

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

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

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

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

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

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

    The function input reads a string and evaluates it as a Python expression. Thus, the comma-separated list becomes a tuple of values, these are passed to add_25(), and this function tries to assign to mylist[i] something. And tuples are immutable, they do not support item assignment (on purpose).

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

  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. Python Tuple (With Examples)

    In Python, we use tuples to store multiple data similar to a list. In this article, we'll learn about Python Tuples with the help of examples. ... TypeError: 'tuple' object does not support item assignment. Delete Tuples We cannot delete individual items of a tuple. However, we can delete the tuple itself using the del statement. For example ...

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

    💥【Python疑难解答】告别"TypeError: 'tuple' object does not support item assignment"的困扰!🔍 你是否曾在Python编程中遇到过这个恼人的错误?😫别担心,我们为你揭秘元组不可变性的真相!🔐 本文将详细解析该错误原因,教你如何巧妙避免🛡️,并深入探讨背后的原理🔬。

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

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

  18. python

    The core problem is that the expression you enter into eval, such as "1, 2, 3" are tuples, which are immutable, i.e., unable to be changed. Additionally, using eval like this is dangerous, and can lead to some confusing errors.

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

    I'm trying to assign a value to the attributes of each feature of a feature layer. To do so I am just iterating through each row using 'arcpy.da.SearchCursor'. #Import geoprocessing. import arcpy #

  20. Pythonのタプル(tuple)の使い方・タプルの操作・例題について

    タプルとは. Pythonのタプル (tuple) は、順序付けられた変更不可のデータの集合を表すデータ型です。リスト (list) に似ていますが、タプルは一度作成すると要素を追加、削除、変更することができません。

  21. python

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  22. os

    This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and ...

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

    TypeError: 'type' object does not support item assignment for "dict[n] = n" Any help or suggestion? Thank you so much! python; Share. Improve this question. ... 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 ...

  24. Type error when accessing a Protobuf map in Python

    I get the "TypeError: RepeatedCompositeFieldContainer object does not support item assignment" when accessing the Protobuf map in Python Proto definition: syntax ...