• Tuple Assignment

Introduction

Tuples are basically a data type in python . These tuples are an ordered collection of elements of different data types. Furthermore, we represent them by writing the elements inside the parenthesis separated by commas. We can also define tuples as lists that we cannot change. Therefore, we can call them immutable tuples. Moreover, we access elements by using the index starting from zero. We can create a tuple in various ways. Here, we will study tuple assignment which is a very useful feature in python.

In python, we can perform tuple assignment which is a quite useful feature. We can initialise or create a tuple in various ways. Besides tuple assignment is a special feature in python. We also call this feature unpacking of tuple.

The process of assigning values to a tuple is known as packing. While on the other hand, the unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.

Moreover, while performing tuple assignments we should keep in mind that the number of variables on the left-hand side and the number of values on the right-hand side should be equal. Or in other words, the number of variables on the left-hand side and the number of elements in the tuple should be equal. Let us look at a few examples of packing and unpacking.

tuple assignment

Tuple Packing (Creating Tuples)

We can create a tuple in various ways by using different types of elements. Since a tuple can contain all elements of the same data type as well as of mixed data types as well. Therefore, we have multiple ways of creating tuples. Let us look at few examples of creating tuples in python which we consider as packing.

Example 1: Tuple with integers as elements

Example 2: Tuple with mixed data type

Example 3: Tuple with a tuple as an element

Example 4: Tuple with a list as an element

If there is only a single element in a tuple we should end it with a comma. Since writing, just the element inside the parenthesis will be considered as an integer.

For example,

Correct way of defining a tuple with single element is as follows:

Moreover, if you write any sequence separated by commas, python considers it as a tuple.

Browse more Topics Under Tuples and its Functions

  • Immutable Tuples
  • Creating Tuples
  • Initialising and Accessing Elements in a Tuple
  • Tuple Slicing
  • Tuple Indexing
  • Tuple Functions

Tuple Assignment (Unpacking)

Unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.

Frequently Asked Questions (FAQs)

Q1. State true or false:

Inserting elements in a tuple is unpacking.

Q2. What is the other name for tuple assignment?

A2. Unpacking

Q3. In unpacking what is the important condition?

A3. The number of variables on the left-hand side and the number of elements in the tuple should be equal.

Q4. Which error displays when the above condition fails?

A4. ValueError: not enough values to unpack

Customize your course in 30 seconds

Which class are you in.

tutor

  • Initialising and Accessing Elements in Tuple

Leave a Reply Cancel reply

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

Download the App

Google Play

Python Land

Python Tuple: How to Create, Use, and Convert

A Python tuple is one of Python’s three built-in sequence data types , the others being lists and range objects. A Python tuple shares a lot of properties with the more commonly known Python list :

  • It can hold multiple values in a single variable
  • It’s ordered: the order of items is preserved
  • A tuple can have duplicate values
  • It’s indexed: you can access items numerically
  • A tuple can have an arbitrary length

But there are significant differences:

  • A tuple is immutable; it can not be changed once you have defined it.
  • A tuple is defined using optional parentheses () instead of square brackets []
  • Since a tuple is immutable, it can be hashed, and thus it can act as the key in a dictionary

Table of Contents

  • 1 Creating a Python tuple
  • 2 Multiple assignment using a Python tuple
  • 3 Indexed access
  • 4 Append to a Python Tuple
  • 5 Get tuple length
  • 6 Python Tuple vs List
  • 7 Python Tuple vs Set
  • 8 Converting Python tuples

Creating a Python tuple

We create tuples from individual values using optional parentheses (round brackets) like this:

Like everything in Python, tuples are objects and have a class that defines them. We can also create a tuple by using the tuple() constructor from that class. It allows any Python iterable type as an argument. In the following example, we create a tuple from a list:

Now you also know how to convert a Python list to a tuple!

Which method is best?

It’s not always easy for Python to infer if you’re using regular parentheses or if you’re trying to create a tuple. To demonstrate, let’s define a tuple holding only one item:

Python sees the number one, surrounded by useless parentheses on the first try, so Python strips down the expression to the number 1. However, we added a comma in the second try, explicitly signaling to Python that we are creating a tuple with just one element.

A tuple with just one item is useless for most use cases, but it demonstrates how Python recognizes a tuple: because of the comma.

If we can use tuple() , why is there a second method as well? The other notation is more concise, but it also has its value because you can use it to unpack multiple lists into a tuple in this way concisely:

The leading * operator unpacks the lists into individual elements. It’s as if you would have typed them individually at that spot. This unpacking trick works for all iterable types if you were wondering!

Multiple assignment using a Python tuple

You’ve seen something called tuple unpacking in the previous topic. There’s another way to unpack a tuple, called multiple assignment. It’s something that you see used a lot, especially when returning data from a function, so it’s worth taking a look at this.

Multiple assignment works like this:

Like using the *, this type of unpacking works for all iterable types in Python, including lists and strings.

As I explained in the Python trick on returning multiple values from a Python function, unpacking tuples works great in conjunction with a function that returns multiple values. It’s a neat way of returning more than one value without having to resort to data classes or dictionaries :

Indexed access

We can access a tuple using index numbers like [0] and [1] :

Append to a Python Tuple

Because a tuple is immutable, you can not append data to a tuple after creating it . For the same reason, you can’t remove data from a tuple either. You can, of course, create a new tuple from the old one and append the extra item(s) to it this way:

What we did was unpack t1 , create a new tuple with the unpacked values and two different strings and assign the result to t again.

Get tuple length

The len() function works on Python tuples just like it works on all other iterable types like lists and strings:

Python Tuple vs List

The most significant difference between a Python tuple and a Python list is that a List is mutable, while a tuple is not. After defining a tuple, you can not add or remove values. In contrast, a list allows you to add or remove values at will. This property can be an advantage; you can see it as write protection. If a piece of data is not meant to change, using a tuple can prevent errors. After all, six months from now, you might have forgotten that you should not change the data. Using a tuple prevents mistakes.

Another advantage is that tuples are faster, or at least that is what people say. I have not seen proof, but it makes sense. Since it’s an immutable data type, a tuple’s internal implementation can be simpler than lists. After all, they don’t need ways to grow larger or insert elements at random positions, which usually is implemented as a linked list . From what I understand, a tuple uses a simple array-like structure in the CPython implementation.

Python Tuple vs Set

The most significant difference between tuples and Python sets is that a tuple can have duplicates while a set can’t. The entire purpose of a set is its inability to contain duplicates. It’s an excellent tool for deduplicating your data.

Converting Python tuples

Convert tuple to list.

Python lists are mutable, while tuples are not. If you need to, you can convert a tuple to a list with one of the following methods.

The cleanest and most readable way is to use the list() constructor:

A more concise but less readable method is to use unpacking. This unpacking can sometimes come in handy because it allows you to unpack multiple tuples into one list or add some extra values otherwise:

Convert tuple to set

Analogous to the conversion to a list, we can use set() to convert a tuple to a set:

Here, too, we can use unpacking:

Convert tuple to string

Like most objects in Python, a tuple has a so-called dunder method, called __str__ , which converts the tuple into a string. When you want to print a tuple, you don’t need to do so explicitly. Python’s print function will call this method on any object that is not a string. In other cases, you can use the str() constructor to get the string representation of a tuple:

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Related articles

  • Python Set: The Why And How With Example Code
  • Python List: How To Create, Sort, Append, Remove, And More
  • Convert a String to Title Case Using Python
  • Python YAML: How to Load, Read, and Write YAML

Python Newsletter

Before you leave, you may want to sign up for my newsletter.

Tips & Tricks News Course discounts

No spam & you can unsubscribe at any time.

Lists and Tuples in Python

Lists and Tuples in Python

Table of Contents

Lists Are Ordered

Lists can contain arbitrary objects, list elements can be accessed by index, lists can be nested, lists are mutable, lists are dynamic, defining and using tuples, tuple assignment, packing, and unpacking.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Lists and Tuples in Python

Lists and tuples are arguably Python’s most versatile, useful data types . You will find them in virtually every nontrivial Python program.

Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.

Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python lists and tuples.

Python Lists

In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ( [] ), as shown below:

The important characteristics of Python lists are as follows:

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.

Each of these features is examined in more detail below.

A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. (You will see a Python data type that is not ordered in the next tutorial on dictionaries.)

Lists that have the same elements in a different order are not the same:

A list can contain any assortment of objects. The elements of a list can all be the same type:

Or the elements can be of varying types:

Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:

A list can contain any number of objects, from zero to as many as your computer’s memory will allow:

(A list with a single object is sometimes referred to as a singleton list.)

List objects needn’t be unique. A given object can appear in a list multiple times:

Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.

Consider the following list:

The indices for the elements in a are shown below:

Diagram of a Python list

Here is Python code to access some elements of a :

Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:

Diagram of a Python list

Slicing also works. If a is a list, the expression a[m:n] returns the portion of a from index m to, but not including, index n :

Other features of string slicing work analogously for list slicing as well:

Both positive and negative indices can be specified:

Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:

You can specify a stride—either positive or negative:

The syntax for reversing a list works the same way it does for strings:

The [:] syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.

If s is a string, s[:] returns a reference to the same object:

Conversely, if a is a list, a[:] returns a new object that is a copy of a :

Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:

The in and not in operators:

The concatenation ( + ) and replication ( * ) operators:

The len() , min() , and max() functions:

It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called an iterable, which you will encounter in more detail in the upcoming tutorial on definite iteration.

By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you can operate on a list literal as well:

For that matter, you can do likewise with a string literal:

You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary depth.

Consider this (admittedly contrived) example:

The object structure that x references is diagrammed below:

Nested lists diagram

x[0] , x[2] , and x[4] are strings, each one character long:

But x[1] and x[3] are sublists:

To access the items in a sublist, simply append an additional index:

x[1][1] is yet another sublist, so adding one more index accesses its elements:

There is no limit, short of the extent of your computer’s memory, to the depth or complexity with which lists can be nested in this way.

All the usual syntax regarding indices and slicing applies to sublists as well:

However, be aware that operators and functions apply to only the list at the level you specify and are not recursive . Consider what happens when you query the length of x using len() :

x has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward x ’s length.

You’d encounter a similar situation when using the in operator:

'ddd' is not one of the elements in x or x[1] . It is only directly an element in the sublist x[1][1] . An individual element in a sublist does not count as an element of the parent list(s).

Most of the data types you have encountered so far have been atomic types. Integer or float objects, for example, are primitive units that can’t be further broken down. These types are immutable , meaning that they can’t be changed once they have been assigned. It doesn’t make much sense to think of changing the value of an integer. If you want a different integer, you just assign a different one.

By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.

The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists.

Modifying a Single List Value

A single value in a list can be replaced by indexing and simple assignment:

You may recall from the tutorial Strings and Character Data in Python that you can’t do this with a string:

A list item can be deleted with the del command:

Modifying Multiple List Values

What if you want to change several contiguous elements in a list at one time? Python allows this with slice assignment , which has the following syntax:

Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of a with <iterable> :

The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.

You can insert multiple elements in place of a single element—just use a slice that denotes only one element:

Note that this is not the same as replacing the single element with a list:

You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n] (a zero-length slice) at the desired index:

You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the del statement with the same slice:

Prepending or Appending Items to a List

Additional items can be added to the start or end of a list using the + concatenation operator or the += augmented assignment operator :

Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a singleton list:

Note: Technically, it isn’t quite correct to say a list must be concatenated with another list. More precisely, a list must be concatenated with an object that is iterable. Of course, lists are iterable, so it works to concatenate a list with another list.

Strings are iterable also. But watch what happens when you concatenate a string onto a list:

This result is perhaps not quite what you expected. When a string is iterated through, the result is a list of its component characters. In the above example, what gets concatenated onto list a is a list of the characters in the string 'corge' .

If you really want to add just the single string 'corge' to the end of the list, you need to specify it as a singleton list:

If this seems mysterious, don’t fret too much. You’ll learn about the ins and outs of iterables in the tutorial on definite iteration.

Methods That Modify a List

Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed below.

Note: The string methods you saw in the previous tutorial did not modify the target string directly. That is because strings are immutable. Instead, string methods return a new string object that is modified as directed by the method. They leave the original target string unchanged:

List methods are different. Because lists are mutable, the list methods shown here modify the target list in place.

a.append(<obj>)

Appends an object to a list.

a.append(<obj>) appends object <obj> to the end of list a :

Remember, list methods modify the target list in place. They do not return a new list:

Remember that when the + operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:

The .append() method does not work that way! If an iterable is appended to a list with .append() , it is added as a single object:

Thus, with .append() , you can append a string as a single entity:

a.extend(<iterable>)

Extends a list with the objects from an iterable.

Yes, this is probably what you think it is. .extend() also adds to the end of a list, but the argument is expected to be an iterable. The items in <iterable> are added individually:

In other words, .extend() behaves like the + operator. More precisely, since it modifies the list in place, it behaves like the += operator:

a.insert(<index>, <obj>)

Inserts an object into a list.

a.insert(<index>, <obj>) inserts object <obj> into list a at the specified <index> . Following the method call, a[<index>] is <obj> , and the remaining list elements are pushed to the right:

a.remove(<obj>)

Removes an object from a list.

a.remove(<obj>) removes object <obj> from list a . If <obj> isn’t in a , an exception is raised:

a.pop(index=-1)

Removes an element from a list.

This method differs from .remove() in two ways:

  • You specify the index of the item to remove, rather than the object itself.
  • The method returns a value: the item that was removed.

a.pop() simply removes the last item in the list:

If the optional <index> parameter is specified, the item at that index is removed and returned. <index> may be negative, as with string and list indexing:

<index> defaults to -1 , so a.pop(-1) is equivalent to a.pop() .

This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. When items are added to a list, it grows as needed:

Similarly, a list shrinks to accommodate the removal of items:

Python Tuples

Python provides another type that is an ordered collection of objects, called a tuple.

Pronunciation varies depending on whom you ask. Some pronounce it as though it were spelled “too-ple” (rhyming with “Mott the Hoople”), and others as though it were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know pronounces these latter as though they rhymed with “supple.”

Tuples are identical to lists in all respects, except for the following properties:

  • Tuples are defined by enclosing the elements in parentheses ( () ) instead of square brackets ( [] ).
  • Tuples are immutable.

Here is a short example showing a tuple definition, indexing, and slicing:

Never fear! Our favorite string and list reversal mechanism works for tuples as well:

Note: Even though tuples are defined using parentheses, you still index and slice tuples using square brackets, just as for strings and lists.

Everything you’ve learned about lists—they are ordered, they can contain arbitrary objects, they can be indexed and sliced, they can be nested—is true of tuples as well. But they can’t be modified:

Why use a tuple instead of a list?

Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)

Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.

There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.

In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the >>> prompt, separated by commas:

Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.

There is one peculiarity regarding tuple definition that you should be aware of. There is no ambiguity when defining an empty tuple, nor one with two or more elements. Python knows you are defining a tuple:

But what happens when you try to define a tuple with one item:

Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression (2) as simply the integer 2 and creates an int object. To tell Python that you really want to define a singleton tuple, include a trailing comma ( , ) just before the closing parenthesis:

You probably won’t need to define a singleton tuple often, but there has to be a way.

When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:

As you have already seen above, a literal tuple containing several items can be assigned to a single object:

When this occurs, it is as though the items in the tuple have been “packed” into the object:

tuple packing

If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the tuple:

tuple unpacking

When unpacking, the number of variables on the left must match the number of values in the tuple:

Packing and unpacking can be combined into one statement to make a compound assignment:

Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:

In assignments like this and a small handful of other situations, Python allows the parentheses that are usually used for denoting a tuple to be left out:

It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.

Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary variable while the swap occurs like this:

In Python, the swap can be done with a single tuple assignment:

As anyone who has ever had to swap values using a temporary variable knows, being able to do it this way in Python is the pinnacle of modern technological achievement. It will never get better than this.

This tutorial covered the basic properties of Python lists and tuples , and how to manipulate them. You will use these extensively in your Python programming.

One of the chief characteristics of a list is that it is ordered. The order of the elements in a list is an intrinsic property of that list and does not change, unless the list itself is modified. (The same is true of tuples, except of course they can’t be modified.)

The next tutorial will introduce you to the Python dictionary: a composite data type that is unordered. Read on!

🐍 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 John Sturtz

John Sturtz

John is an avid Pythonista and a member of the Real Python tutorial team.

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: basics python

Recommended Video Course: Lists and Tuples in Python

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

Already have an account? Sign-In

python tuple assignment

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 Sets
  • 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

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.

Related Tutorials

Python Library

Python Tutorial

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Tuples

Tuples in Python

  • Python - Create a List of Tuples
  • Create a tuple from string and list - Python
  • Access front and rear element of Python tuple
  • Python - Element Index in Range Tuples
  • Unpacking a Tuple in Python
  • Python | Unpacking nested tuples
  • Python | Slice String from Tuple ranges
  • Python - Clearing a tuple
  • Python program to remove last element from Tuple
  • Python | Removing duplicates from tuple
  • Python - AND operation between Tuples
  • Python - Sum of tuple elements
  • Python | Ways to concatenate tuples
  • Python | Repeating tuples N times
  • Python Membership and Identity Operators
  • Python | Compare tuples
  • Python | Join tuple elements in a list
  • Python - Join Tuples if similar initial element
  • Python - Create list of tuples using for loop
  • How we can iterate through list of tuples in Python
  • Python Tuple Methods
  • Python Tuple Exercise

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.

Creating Python Tuples

There are various ways by which you can create a tuple in Python . They are as follows:

  • Using round brackets
  • With one item
  • Tuple Constructor

Create Tuples using Round Brackets ()

To create a tuple we will use () operators.

Create a Tuple With One Item

Python 3.11 provides us with another way to create a Tuple.

Here, in the above snippet we are considering a variable called values which holds a tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than one int or str.

Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Let us see an example of the same.

Tuple Constructor in Python

To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

What is Immutable in Tuples?

Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and allow duplicate values. Some Characteristics of Tuples in Python.

  • We can find items in a tuple since finding any item does not make changes in the tuple.
  • One cannot add items to a tuple once it is created. 
  • Tuples cannot be appended or extended.
  • We cannot remove items from a tuple once it is created. 

Let us see this with an example.

Python tuples are ordered and we can access their elements using their index values. They are also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple, so when we tried to add an element at index 1, it generated the error.

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

  • Using a positive index
  • Using a negative index

Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we will use the negative index within [].

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

  • Concatenation
  • Finding the length
  • Multiple Data Types with tuples
  • Conversion of lists to tuples

Tuples in a Loop

Concatenation of python tuples.

To Concatenation of Python Tuples, we will use plus operators(+).

Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that tuple.

Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’. 

Slicing Tuples in Python

Slicing a Python tuple means dividing a tuple into small tuples using the indexing method.

In this example, we sliced the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.

Note: In Python slicing, the end index provided is not included.

Deleting a Tuple in Python

In this example, we are deleting a tuple using ‘ del’ keyword . The output will be in the form of error because after deleting the tuple, it will give a NameError.

Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.

Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.

Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.

Converting a List to a Tuple

We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.

Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.

We can also create a tuple with a single element in it using loops .

Please Login to comment...

Similar reads.

  • School Programming
  • python-tuple

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

python tuple assignment

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 13.1 Introduction
  • 13.2 Tuple Packing
  • 13.3 Tuple Assignment with Unpacking
  • 13.4 Tuples as Return Values
  • 13.5 Unpacking Tuples as Arguments to Function Calls
  • 13.6 Glossary
  • 13.7 Exercises
  • 13.8 Chapter Assessment
  • 13.2. Tuple Packing" data-toggle="tooltip">
  • 13.4. Tuples as Return Values' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

13.3. Tuple Assignment with Unpacking ¶

Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

This does the equivalent of seven assignment statements, all on one easy line.

Naturally, the number of variables on the left and the number of values on the right have to be the same.

Unpacking into multiple variable names also works with lists, or any other sequence type, as long as there is exactly one value for each variable. For example, you can write x, y = [3, 4] .

13.3.1. Swapping Values between Variables ¶

This feature is used to enable swapping the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b :

Tuple assignment solves this problem neatly:

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

13.3.2. Unpacking Into Iterator Variables ¶

Multiple assignment with unpacking is particularly useful when you iterate through a list of tuples. You can unpack each tuple into several loop variables. For example:

On the first iteration the tuple ('Paul', 'Resnick') is unpacked into the two variables first_name and last_name . One the second iteration, the next tuple is unpacked into those same loop variables.

13.3.3. The Pythonic Way to Enumerate Items in a Sequence ¶

When we first introduced the for loop, we provided an example of how to iterate through the indexes of a sequence, and thus enumerate the items and their positions in the sequence.

We are now prepared to understand a more pythonic approach to enumerating items in a sequence. Python provides a built-in function enumerate . It takes a sequence as input and returns a sequence of tuples. In each tuple, the first element is an integer and the second is an item from the original sequence. (It actually produces an “iterable” rather than a list, but we can use it in a for loop as the sequence to iterate over.)

The pythonic way to consume the results of enumerate, however, is to unpack the tuples while iterating through them, so that the code is easier to understand.

Check your Understanding

Consider the following alternative way to swap the values of variables x and y. What’s wrong with it?

  • You can't use different variable names on the left and right side of an assignment statement.
  • Sure you can; you can use any variable on the right-hand side that already has a value.
  • At the end, x still has it's original value instead of y's original value.
  • Once you assign x's value to y, y's original value is gone.
  • Actually, it works just fine!

With only one line of code, assign the variables water , fire , electric , and grass to the values “Squirtle”, “Charmander”, “Pikachu”, and “Bulbasaur”

With only one line of code, assign four variables, v1 , v2 , v3 , and v4 , to the following four values: 1, 2, 3, 4.

If you remember, the .items() dictionary method produces a sequence of tuples. Keeping this in mind, we have provided you a dictionary called pokemon . For every key value pair, append the key to the list p_names , and append the value to the list p_number . Do not use the .keys() or .values() methods.

The .items() method produces a sequence of key-value pair tuples. With this in mind, write code to create a list of keys from the dictionary track_medal_counts and assign the list to the variable name track_events . Do NOT use the .keys() method.

Python Programming

Python Tuple Exercise with Solutions

Updated on:  December 8, 2021 | 96 Comments

A tuple is an immutable object in Python that can’t be changed. Tuples are also sequences, just like Python lists .

This Python Tuple exercise aims to help you to learn and practice tuple operations. All questions are tested on Python 3.

Also Read :

  • Python Tuples
  • Python Tuple Quiz

This Tuple exercise includes the following : –

  • It contains 10 questions and solutions provided for each question.
  • It has questions to practice Python tuple assignments, programs, and challenges.
  • This tuple exercise covers tuple creation, operations, unpacking of a tuple.

When you complete each question, you get more familiar with Python tuple. Let us know if you have any alternative solutions. It will help other developers.

  • Use Online Code Editor to solve exercise questions .
  • Read the complete guide on Python Tuples to solve this exercise.

Table of contents

Exercise 1: reverse the tuple, exercise 2: access value 20 from the tuple, exercise 3: create a tuple with single item 50, exercise 4: unpack the tuple into 4 variables, exercise 5: swap two tuples in python, exercise 6: copy specific elements from one tuple to a new tuple, exercise 7: modify the tuple.

  • Exercise 8: Sort a tuple of tuples by 2nd item

Exercise 9: Counts the number of occurrences of item 50 from a tuple

Exercise 10: check if all items in the tuple are the same.

Expected output:

Use tuple slicing to reverse the given tuple. Note: the last element starts at -1.

The given tuple is a nested tuple. write a Python program to print the value 20.

The given tuple is a nested tuple. Use indexing to locate the specified item.

Write a program to unpack the following tuple into four variables and display each variable.

Write a program to copy elements 44 and 55 from the following tuple into a new tuple.

Given is a nested tuple. Write a program to modify the first item (22) of a list inside a following tuple to 222

The given tuple is a nested tuple. Use indexing to locate the specified item and modify it using the assignment operator.

Exercise 8: Sort a tuple of tuples by 2 nd item

Use the count() method of a tuple.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

python tuple assignment

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

python tuple assignment

March 2, 2024 at 1:29 am

Thank you, Vishal, for creating this website and simplifying complex concepts and topics in an easily understandable manner. I have bookmarked your website, and whenever I encounter any issues or doubts, I refer to the relevant topic on your site for assistance. Once again, thank you very much.

python tuple assignment

November 29, 2023 at 6:53 pm

Another answer for number 10 , may be

tuple1 = (45, 45, 45, 45) print(all(tuple1))

python tuple assignment

June 30, 2024 at 12:47 am

No because if you change any of the 45 to any other non zero value, it’ll still give True as all gives true if all values are non zero and not necessary same

python tuple assignment

November 18, 2023 at 10:06 am

Q 10. Another solution:

tuple1 = (45, 45, 45, 45)

print(all(tuple1))

Same answer as mine

python tuple assignment

March 18, 2024 at 4:12 pm

It is showing error when we are putting an extra value i.e 46 in the tuple then also it is giving True which is wrong.

tuple1 = (45, 45, 45, 45,46)

it should return False but giving output as True.

python tuple assignment

August 31, 2023 at 2:56 pm

Another solution for exercise 10 : tuple1 = (45, 45, 45, 45)

if tuple1.count(tuple1[0]) == len(tuple1): print(“are all the same”) else: print(“are all not the same”)

python tuple assignment

November 8, 2023 at 5:11 pm

i have an other solution tuple1 = (45, 45, 45, 45) a, b, c, d = tuple1 print(a is b is c is d) #it is not that good but it does the job

python tuple assignment

April 13, 2024 at 3:53 pm

Super it works for me.

python tuple assignment

June 4, 2024 at 11:49 pm

what if we have 100 or 1000 values?

python tuple assignment

December 8, 2023 at 5:48 pm

def is_same_elems(tpl): return len(set(tpl)) == 1

python tuple assignment

August 24, 2023 at 12:04 pm

thank you so much, that was very helpful

python tuple assignment

May 10, 2023 at 7:15 pm

Create a pandas dataframe from list of marks of semester 1, 2, 3, and 4, which are given below and index them as Maths, Physics, and Chemistry. Semester 1: [84, 99, 95] Semester 2: [70, 89, 85] Semester 3: [85, 90, 92] Semester 4: [91, 87, 79]

May 9, 2023 at 8:18 pm

print non repeated integer from the list. numbers=[2,4,2,3,4,6,3,7,6]

python tuple assignment

May 10, 2023 at 4:24 am

from collections import Counter

numbers=[2,4,2,3,4,6,3,7,6] new_numbers = Counter(numbers) n = [number[0] for number in new_numbers.items() if number[1] < 2] print(n)

May 10, 2023 at 7:18 pm

Thanks for the response but I got error as (No module named ‘counter’)

December 8, 2023 at 5:57 pm

def print_non_repeated_elems(nums): return [i_el for i_el in nums if nums.count(i_el) == 1]

python tuple assignment

June 15, 2023 at 1:11 pm

for i in numbers: if numbers.count(i) == 1: print(i)

python tuple assignment

July 2, 2023 at 6:34 pm

numbers=[2,4,2,3,4,6,3,7,6] L=[] for i in numbers: if numbers.count(i)>1: continue else: L.append(i) print(L)

May 9, 2023 at 8:16 pm

[(‘a’,50),(‘b’,60),(‘c’,40)] , get the values in descending order o/p=[‘b’,’a’,’c’]

May 10, 2023 at 5:08 am

list1 = [('a', 50), ('b', 60), ('c', 40)] new_list = [x[0] for x in (sorted(list1, key=lambda x: x[1], reverse=True))] print(new_list)

May 10, 2023 at 7:09 pm

python tuple assignment

November 5, 2022 at 5:15 am

Exercise 6 – alternative approach (please re-insert pre tags if these are stripped)

tuple1 = (11, 22, 33, 44, 55, 66)

def copy_elements_tuple(*elements): new_tuple = (elements) print(new_tuple)

copy_elements_tuple(44,55)

python tuple assignment

November 4, 2022 at 7:56 am

pls guide how to use to comment a code?

python tuple assignment

March 28, 2023 at 2:28 pm

If you are using vs code then click “ctrl + /”. For single line comment use “#” and for multiline comment use ”’ this is inside multiline comment ”’

November 4, 2022 at 7:55 am

tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29)) sorted_tuple = tuple(sorted(tuple1,key=lambda x:x[1])) print(sorted_tuple)

python tuple assignment

October 27, 2022 at 8:08 pm

EX6: Copy Specific elements

tuple1 = (11, 22, 33, 44, 55, 66) tuple2 = tuple() for i in tuple1: if i == 44 or i == 55: tuple2 += i, print(tuple2) /

October 27, 2022 at 8:11 pm

Make sure we have a comma after i in for loop

python tuple assignment

November 14, 2022 at 7:24 pm

Suppose i want to copy 44 and 55

Use the slice method to decrease no.of lines.

tuple2 = tuple1[3:5] print(tuple2)

output: (44,55)

python tuple assignment

October 21, 2022 at 3:34 pm

For exercise 6: tuple1=[11,22,33,44,55,66] I think the solution would be tuple2=tuple1[-3:-1] or tuple2=tuple1[3:5]

python tuple assignment

February 2, 2023 at 6:00 pm

Above program why we use -1

python tuple assignment

March 3, 2023 at 5:50 pm

negative indexing is used we when we used index from right side this happens same with string, list and tuple data types. we can use negative indexing or positive indexing when we count from right to left indexing start from -1 and so on, but when we count from left to right we use positive indexing 0 and so on…. Hope you understand….

python tuple assignment

June 17, 2023 at 3:37 pm

simple formula in case of negative tuple2=tuple1[len(tuple1)-3:len(tuple1)-1]=tuple1[6-3:6-1]=tuple1[3:5]

October 21, 2022 at 3:30 pm

For Exercise 7, i don’t think we can modify tuple directly as Tuple is unchangeable. For updation or modification, tuple needs to be converted to list, update the changes and revert back

python tuple assignment

September 4, 2022 at 9:59 am

is this correct??

python tuple assignment

September 12, 2022 at 10:56 pm

September 13, 2022 at 10:36 am

python tuple assignment

August 24, 2022 at 8:33 pm

This solution to Ex. 10 seems much simpler and straightforward.

python tuple assignment

September 2, 2022 at 2:55 pm

agreed. I took the same approach.

python tuple assignment

August 20, 2022 at 2:00 pm

Another solution for question 10

python tuple assignment

July 22, 2022 at 3:34 pm

This is my answer for Q10

python tuple assignment

July 17, 2022 at 2:03 pm

python tuple assignment

September 29, 2022 at 11:23 pm

python tuple assignment

June 13, 2022 at 6:31 pm

September 2, 2022 at 3:00 pm

I don’t believe it’s the correct solution. this logic works only for tuples with item 1.

python tuple assignment

June 8, 2022 at 12:19 am

Another solution for exercise 10:

python tuple assignment

March 28, 2023 at 2:32 pm

Here is my solution for exercise 10 # Exercise 10: Check if all items in the tuple are the same tuple1 = (45, 45, 45, 45) a = tuple1.count(tuple1[0]) if(a==len(tuple1)): print(True) else: print(False)

June 7, 2022 at 11:49 pm

Another solution for exercise 8:

June 7, 2022 at 12:52 pm

python tuple assignment

April 1, 2022 at 10:01 am

Exercise 6:

October 27, 2022 at 8:17 pm

You can add it directly to new tuple # tuple1 = (11, 22, 33, 44, 66, 55) # tuple2 = tuple() # for i in tuple1: # if i == 44 or i == 55: # tuple2 += i,

Make sure you don’t forget the comma after += I in if the loop

python tuple assignment

March 6, 2022 at 3:04 pm

What does lambda x: x[1] mean?

python tuple assignment

June 6, 2022 at 6:30 pm

Sorted function is mapping iterable to lambda and then sorting it out. so Lambda takes x as argument to which element from iterable that is tuple1 is being supplied which is a tuple i.e. for first iteration (‘a’,23) and so on. So to access number from it indexing of x is done i.e. x[1]. and at the end sorting is applied on this number.

python tuple assignment

January 21, 2022 at 4:36 pm

i think this is better than your solution what do you think ?

python tuple assignment

January 8, 2022 at 10:44 am

the solution for exercise 8 went over my head as i have still not learnt lamda expressions well. My solution was:

python tuple assignment

July 3, 2022 at 6:05 pm

how much time do you guys take on an average to solve exercises in pynative??

python tuple assignment

December 29, 2021 at 5:21 pm

Hi exercise5 has second solution:

python tuple assignment

April 6, 2022 at 5:39 pm

as a developer you are required to do tasks efficiently in less time and less lines of codes to be written

python tuple assignment

October 15, 2021 at 7:04 pm

This code also works

python tuple assignment

October 26, 2021 at 3:08 pm

but it will print (True True True True False) maybe we should try something like while loop. How about this?

October 26, 2021 at 3:09 pm

Ps: sorry not a while loop, just a condition in the start.

python tuple assignment

May 5, 2021 at 9:05 pm

Hi,Vishal! Very useful website and good quality content… Your website helps strength my basis in python…. Thanks a lot!

python tuple assignment

March 24, 2021 at 8:56 pm

I think its a good solution for Exercise 10

python tuple assignment

May 31, 2021 at 5:52 am

Thanks for useful exercises. How about below syntax for Exercise 10

python tuple assignment

March 8, 2021 at 9:32 pm

Very useful site… but it would have been even better if you provided an explanation after each solution

python tuple assignment

March 9, 2021 at 8:08 pm

Thank you for the suggestion, Yes we will definitely add an explanation.

python tuple assignment

February 27, 2021 at 2:07 am

Hi Vishal! Most of signs are very clear and nice. And all can be learned using only Your homepage. Thanks a lot!

March 2, 2021 at 8:53 pm

Thank you, Marton.

python tuple assignment

February 14, 2021 at 1:02 am

I think It is a good solution. It’s working for all variants.

python tuple assignment

February 8, 2021 at 2:06 am

Another solution to question 10:

python tuple assignment

December 24, 2021 at 5:22 pm

This already works,

I’m not sure the if statement part is useful here. Great solution though

python tuple assignment

December 24, 2020 at 9:42 pm

python tuple assignment

October 27, 2020 at 6:19 pm

Hey,Vishal I’m Gulshan and want to really appericate for making this website because it helped me in working on basics of python which is very necessary to learn before moving forward with any language.

python tuple assignment

October 13, 2020 at 10:58 pm

I had learnt python basics from Coursera and trust me most of the thing i saw here, wasn’t covered in coursera. Thank you 🙂

October 16, 2020 at 4:47 pm

I am glad you liked it

December 24, 2021 at 5:28 pm

Hi Vishal, same here, I learnt from Codecademy,

When I came across your blog, I felt like I had learnt nothing so far. Restarted everything from scratch. Thank you so much and great work.

January 2, 2022 at 11:08 am

Thank you, Danilo.

python tuple assignment

June 24, 2020 at 4:43 am

SR: if you pass empty tuple, it will show Index Error

python tuple assignment

June 11, 2020 at 5:20 pm

what about this code. is this correct way or wrong way for best programmer

python tuple assignment

June 17, 2021 at 9:46 pm

Not All value are same

python tuple assignment

September 8, 2021 at 8:46 pm

September 8, 2021 at 8:50 pm

python tuple assignment

May 29, 2020 at 9:37 am

Hi Vishal, I’ve been learning Python for about 6 months and I am flustered. I don’t know any programmers but a few videos I’ve subscribed to on Youtube. I’ve have tried to research google for myself and discovered you. I was working with Udemy and kept getting confused. I am trying to write a simple program for myself. I want to randomly select a file from a directory, yet I am hitting a wall. I have Python 3.7 and here is my sample.

My results: TypeError: expected str, bytes, or os.PathLike object, not a tuple

May 31, 2020 at 11:10 am

Hey, Derrick, you can try this code

python tuple assignment

May 28, 2020 at 9:29 pm

WIll this work???

python tuple assignment

October 10, 2020 at 8:23 pm

this is working Keerthi

October 10, 2020 at 8:27 pm

sry, there should be indentations in those print statements

python tuple assignment

October 16, 2021 at 5:55 pm

It is a good solution for example 10?

python tuple assignment

May 6, 2020 at 1:33 pm

I have tried below the solution for Question No.10, Please let me know if its correct way to check

May 7, 2020 at 8:31 pm

Hey, Nupur, this will also work, but the solution you provided is not efficient when tuple contains more elements. Thank you

June 24, 2020 at 4:39 am

Nupur: Wrong: Solution Try with tuple1 = (45,46,46,45)

python tuple assignment

April 14, 2020 at 3:28 pm

The solution (or task) in Exercise Question 10 is wrong. It will return true even if values are different:

Output: True

April 15, 2020 at 12:24 am

Alex, You are right. Now, I have updated the answer. Can you please check

python tuple assignment

May 13, 2020 at 11:30 am

Another solution:

June 24, 2020 at 4:42 am

SR: If you pass empty tuple, your solution will show IndexError

python tuple assignment

June 24, 2020 at 4:45 am

Oops, I take that back. I had another issue.

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Digital Design Journal

Tuple Assignment Python [With Examples]

Tuple assignment is a feature that allows you to assign multiple variables simultaneously by unpacking the values from a tuple (or other iterable) into those variables.

Tuple assignment is a concise and powerful way to assign values to multiple variables in a single line of code.

Here’s how it works:

In this example, the values from the my_tuple tuple are unpacked and assigned to the variables a , b , and c in the same order as they appear in the tuple.

Tuple assignment is not limited to tuples; it can also work with other iterable types like lists:

Tuple assignment can be used to swap the values of two variables without needing a temporary variable:

Tuple assignment is a versatile feature in Python and is often used when you want to work with multiple values at once, making your code more readable and concise.

Tuple Assignment Python Example

Here are some examples of tuple assignment in Python:

Example 1: Basic Tuple Assignment

Example 2: Multiple Variables Assigned at Once

Example 3: Swapping Values

Example 4: Unpacking a Tuple Inside a Loop

Example 5: Ignoring Unwanted Values

These examples demonstrate various uses of tuple assignment in Python, from basic variable assignment to more advanced scenarios like swapping values or ignoring unwanted elements in the tuple. Tuple assignment is a powerful tool for working with structured data in Python.

  • Python Tuple Vs List Performance
  • Subprocess Python Stdout
  • Python Subprocess Stderr
  • Python Asyncio Subprocess [Asynchronous Subprocesses]
  • Subprocess.popen And Subprocess.run
  • Python Subprocess.popen
  •  Difference Between Subprocess Popen And Call
  • 5 Tuple Methods in Python [Explained]
  • Python List to Tuple
  • Python Tuple Append
  • Python Unpack Tuple Into Arguments
  • Python Concatenate Tuples

Aniket Singh

Aniket Singh holds a B.Tech in Computer Science & Engineering from Oriental University. He is a skilled programmer with a strong coding background, having hands-on experience in developing advanced projects, particularly in Python and the Django framework. Aniket has worked on various real-world industry projects and has a solid command of Python, Django, REST API, PostgreSQL, as well as proficiency in C and C++. He is eager to collaborate with experienced professionals to further enhance his skills.

Leave a Comment Cancel reply

python tuple assignment

  • Subscription

Python Tuples: A Step-by-Step Tutorial (with 14 Code Examples)

When working with data collections, we occasionally encounter situations where we want to ensure it's impossible to change the sequence of objects after creation.

For instance, when reading data from a database in Python, we can represent each table record as an ordered and unchangeable sequence of objects since we don't need to alter the sequence later. Python has a built-in sequence data type to store data in an unchangeable object, called a tuple .

After you finish this Python tutorial, you'll know the following:

  • How to work with tuples in Python
  • The difference between tuples and lists in Python
  • The basic uses of tuples

In this tutorial, we assume you know the fundamentals of Python, including variables, data types, and basic structures. If you're not familiar with these or would like to review, you might like to try our Python Basics for Data Analysis – Dataquest .

Let's dive in.

What Is a Python Tuple?

A tuple represents a sequence of any objects separated by commas and enclosed in parentheses. A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items.

Let's take a look at some examples of Python tuples:

  • () — an empty tuple
  • (1.0, 9.9, 10) — a tuple containing three numeric objects
  • ('Casey', 'Darin', 'Bella', 'Mehdi') — a tuple containing four string objects
  • ('10', 101, True) — a tuple containing a string, an integer, and a Boolean object

Also, other objects like lists and tuples can comprise a tuple, like this:

The code above creates a tuple containing an integer, a list, a tuple, and a float number. The following code returns the entire tuple and its data type.

However, ('A') is not a tuple. Let’s look at its data type:

So, how can we declare a single-value tuple? The answer is easy. We need to add an extra comma just before the closing parenthesis, like this: ('A',) The trailing comma means that the parentheses are holding a single-value tuple, not to increase the precedence of a mathematical operation.

Indexing and Slicing a Tuple

As mentioned earlier, because a tuple is a sequence of objects, we can access these objects through indexing. As with strings, the index of the first element is 0, the second element is 1, and so on. Let’s try indexing a tuple:

In the code above, the first and second statements return the values of the tuple's first and last elements. The last statement prints out the data type of the second element of the tuple, which is a list object.

Furthermore, the following piece of code shows how to retrieve the second element of the inner tuple, at index 2.

This means that we can access an element stored in an inner tuple (a tuple stored inside another tuple) by doing a series of indexing operations.

Slicing a tuple is as simple as slicing a Python string or a list with the same rules. To get a range of elements within a tuple, we can specify a range of indices to retrieve by selecting where to start (inclusive) and end (exclusive) the range.

Let’s take a look at some examples:

The first line of the code declares a tuple of integer values. Although it’s unusual, it’s another way to declare a tuple by providing a sequence of objects separated by commas without enclosing them in parentheses. The subsequent statements print out different slices of the tuple, as shown.

If you’re not familiar with indexing and slicing a sequence object in Python or would like to review, there is a good tutorial on the Dataquest blog at Tutorial: Demystifying Python Lists .

To concatenate two or more tuples, we can use + sign as with strings. For example, the following code concatenates two tuples:

Moreover, multiplying a tuple by an integer produces a tuple containing the original tuple repeated that many times. Let’s try it:

Zipping Tuples

The zip() method takes multiple sequence objects and returns an iterable object by matching their elements. To learn more about zipping tuples, consider the following example.

Let's assume that we have three different tuples containing the personal details of four customers. We want to create a single tuple that holds the corresponding data for each customer, including their first name, last name, and age, in the form of separate tuples:

We declare the first_name , last_name , and ages tuples in the code above. The zip() method takes the three tuples and returns a zip object, which is an iterator. To consume the iterator object, we need to convert it to either a list or a tuple, like this:

The customers tuple consists of four tuple objects, each of which belongs to a customer.

Unpacking Tuples

Unpacking a tuple allows us to extract the tuple elements and assign them to named variables. Let’s try it:

The code above retrieves the tuple elements stored at index 2 of the customers tuple and assigns them to the first_name , last_name , and age variables.

Difference Between Tuples and Lists in Python

Besides the intuitive difference between tuples and lists, as mentioned before, tuples are immutable, so unlike lists, tuples cannot be modified. However, some technical differences make tuples an undeniable asset in Python programming.

The first difference that makes lists more preferable iterable objects than tuples is that a list object provides more methods. But the extra functionality comes at a price. Let’s first look at the size of the occupied memory of each object in the code below, then discuss why tuples are the better choice in some situations.

We can see that a list object occupies more memory than a tuple object. The significance of occupying less memory becomes more apparent when we work with big data, which means immutability makes significant optimization when working with a large amount of data. In addition to occupying less memory, processing tuple objects is much faster than lists, especially when dealing with millions and millions of sequence objects.

Usage of Python Tuples

This section will discuss two exciting ways of using tuples in practice. Let’s explore them.

Tuple Element Swapping

We can use tuples to swap the values associated with variables only if the variables are tuple elements. Let’s try it out:

The value of y is assigned to the x variable, and the x value is simultaneously assigned to the y . It’s a more Pythonic way to swap values.

Returning More Than One Value from a Function

Functions can only return a single value. However, we can use a tuple and put as many values as we need inside it, then return the tuple object as the function’s return value. Let’s see how we can use a tuple to return multiple values from a function in the following code:

The sum_and_avg() function calculates the sum and average of three numeric values. The function returns s and a , which are the two values that it calculates, in the context of the tuple object. In fact, the function only returns a single value, which is a tuple object containing multiple values. We also used the tuple unpacking technique to extract the values in the returned tuple object, then print them out.

This tutorial covered how to create tuple objects, as well as many aspects of Python tuples, such as indexing, slicing, zipping, unpacking, etc. We also discussed the difference between tuples and lists. Using Python tuples properly will definitely make our code more efficient and robust.

More learning resources

Python range tutorial: learn to use this helpful built-in function, an intro to logistic regression in python (w/ 100+ code examples).

Learn data skills 10x faster

Headshot

Join 1M+ learners

Enroll for free

  • Data Analyst (Python)
  • Gen AI (Python)
  • Business Analyst (Power BI)
  • Business Analyst (Tableau)
  • Machine Learning
  • Data Analyst (R)

Guru99

Python TUPLE – Pack, Unpack, Compare, Slicing, Delete, Key

Steve Campbell

What is Tuple Matching in Python?

Tuple Matching in Python is a method of grouping the tuples by matching the second element in the tuples. It is achieved by using a dictionary by checking the second element in each tuple in python programming. However, we can make new tuples by taking portions of existing tuples.

Tuple Syntax

To write an empty tuple, you need to write as two parentheses containing nothing-

For writing tuple for a single value, you need to include a comma, even though there is a single value. Also at the end you need to write semicolon as shown below.

Tuple indices begin at 0, and they can be concatenated, sliced and so on.

Tuple Assignment

Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have assigned tuple 1 with the persons information like name, surname, birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).

For Example,

(name, surname, birth year, favorite movie and year, profession, birthplace) = Robert

Here is the code,

  • Tuple 1 includes list of information of Robert
  • Tuple 2 includes list of numbers in it
  • We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
  • Run the code- It gives name Robert for first tuple while for second tuple it gives number (2,3 and 4)

Packing and Unpacking

  • In packing, we place value into a new tuple while in unpacking we extract those values back into variables.

Comparing tuples

  • A comparison operator in Python can work with tuples.

The comparison starts with a first element of each tuple. If they do not compare to =,< or > then it proceed to the second element and so on.

It starts with comparing the first element from each of the tuples

Let’s study this with an example-

Case1: Comparison starts with a first element of each tuple. In this case 5>1, so the output a is bigger

Case 2: Comparison starts with a first element of each tuple. In this case 5>5 which is inconclusive. So it proceeds to the next element. 6>4, so the output a is bigger

Case 3: Comparison starts with a first element of each tuple. In this case 5>6 which is false. So it goes into the else block and prints “b is bigger.”

  • Using tuples as keys in dictionaries

Since tuples are hashable, and list is not, we must use tuple as the key if we need to create a composite key to use in a dictionary.

Example : We would come across a composite key if we need to create a telephone directory that maps, first-name, last-name, pairs of telephone numbers, etc. Assuming that we have declared the variables as last and first number, we could write a dictionary assignment statement as shown below:

Inside the brackets, the expression is a tuple. We could use tuple assignment in a for loop to navigate this dictionary.

This loop navigates the keys in the directory, which are tuples. It assigns the elements of each tuple to last and first and then prints the name and corresponding telephone number.

Tuples and dictionary

Dictionary can return the list of tuples by calling items, where each tuple is a key value pair.

Deleting Tuples

Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple. But deleting tuple entirely is possible by using the keyword

Slicing of Tuple

To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing. Slicing is not only applicable to tuple but also for array and list.

The output of this code will be (‘c’, ‘d’).

Here is the Python 2 Code for all above example

Built-in functions with Tuple

To perform different task, tuple allows you to use many built-in functions like all(), any(), enumerate(), max(), min(), sorted(), len(), tuple(), etc.

Advantages of tuple over list

  • Iterating through tuple is faster than with list, since tuples are immutable.
  • Tuples that consist of immutable elements can be used as key for dictionary, which is not possible with list
  • If you have data that is immutable, implementing it as tuple will guarantee that it remains write-protected

Python has tuple assignment feature which enables you to assign more than one variable at a time.

  • Packing and Unpacking of Tuples
  • Tuples are hashable, and list are not
  • We must use tuple as the key if we need to create a composite key to use in a dictionary
  • Dictionary can return the list of tuples by calling items, where each tuple is a key value pair
  • Tuples are immutable and cannot be deleted. You cannot delete or remove items from a tuple. But deleting tuple entirely is possible by using the keyword “del”
  • To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing
  • Online Python Compiler (Editor / Interpreter / IDE) to Run Code
  • PyUnit Tutorial: Python Unit Testing Framework (with Example)
  • How to Install Python on Windows [Pycharm IDE]
  • Hello World: Create your First Python Program
  • Python Variables: How to Define/Declare String Variable Types
  • Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase
  • Dictionary in Python with Syntax & Example
  • Operators in Python – Logical, Arithmetic, Comparison
  • Python »
  • 3.12.4 Documentation »
  • The Python Tutorial »
  • 5. Data Structures
  • Theme Auto Light Dark |

5. Data Structures ¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists ¶

The list data type has some more methods. Here are all of the methods of list objects:

Add an item to the end of the list. Equivalent to a[len(a):] = [x] .

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .

Remove the first item from the list whose value is equal to x . It raises a ValueError if there is no such item.

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.

Remove all items from the list. Equivalent to del a[:] .

Return zero-based index in the list of the first item whose value is equal to x . Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Return the number of times x appears in the list.

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

Reverse the elements of the list in place.

Return a shallow copy of the list. Equivalent to a[:] .

An example that uses most of the list methods:

You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . [ 1 ] This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, [None, 'hello', 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.

5.1.1. Using Lists as Stacks ¶

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

5.1.2. Using Lists as Queues ¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

5.1.3. List Comprehensions ¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

or, equivalently:

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

and it’s equivalent to:

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

List comprehensions can contain complex expressions and nested functions:

5.1.4. Nested List Comprehensions ¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

The following list comprehension will transpose rows and columns:

As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:

which, in turn, is the same as:

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement ¶

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

del can also be used to delete entire variables:

Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.

5.3. Tuples and Sequences ¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple .

A tuple consists of a number of values separated by commas, for instance:

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing : the values 12345 , 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets ¶

Python also includes a data type for sets . A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

Similarly to list comprehensions , set comprehensions are also supported:

5.5. Dictionaries ¶

Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys , which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

5.6. Looping Techniques ¶

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

5.7. More on Conditions ¶

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .

Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types ¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Table of Contents

  • 5.1.1. Using Lists as Stacks
  • 5.1.2. Using Lists as Queues
  • 5.1.3. List Comprehensions
  • 5.1.4. Nested List Comprehensions
  • 5.2. The del statement
  • 5.3. Tuples and Sequences
  • 5.5. Dictionaries
  • 5.6. Looping Techniques
  • 5.7. More on Conditions
  • 5.8. Comparing Sequences and Other Types

Previous topic

4. More Control Flow Tools

  • Report a Bug
  • Show Source

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python - tuple methods, tuple methods.

Python has two built-in methods that you can use on tuples.

Method Description
Returns the number of times a specified value occurs in a tuple
Searches the tuple for a specified value and returns the position of where it was found

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Python tuple assignment and checking in conditional statements [duplicate]

So I stumbled into a particular behaviour of tuples in python that I was wondering if there is a particular reason for it happening.

While we are perfectly capable of assigning a tuple to a variable without explicitely enclosing it in parentheses:

we are not able to print or check in a conditional if statement the variable containing the tuple in the previous fashion (without explicitely typing the parentheses):

Does anyone why? Thanks in advance and although I didn't find any similar topic please inform me if you think it is a possible dublicate. Cheers, Alex

  • if-statement

Alex Koukoulas's user avatar

  • 1 Essentially commas when used in assignments are what actually create tuples, not the parentheses. However, eq operator is a function that takes only single argument, and when you pass it values separated by commas, it takes it as passing arg rather than passing the tuple 'foo','bar' . Wrapping in parens forces the tuple assignment operator to happen before the evaluation of arg , so it behaves as expected. –  aruisdante Commented Mar 16, 2014 at 0:32
  • 1 To put it another way, if you think of foo_bar_tuple == 'foo','bar' as actually being foo_bar_tuple.__eq__('foo', 'bar') , you can immediately see why you need to wrap in parens to make it work –  aruisdante Commented Mar 16, 2014 at 0:35
  • @aruisdante: Your statement that foo_bar_tuple == 'foo', 'bar' is equivalent to foo_bar_tuple.__eq__('foo', 'bar') is incorrect. The comparison is happening with just the 'foo' string ( foo_bar_tuple.__eq__('foo') , which is False ) and 'bar' is left as a separate expression. –  Blckknght Commented Mar 16, 2014 at 1:01

3 Answers 3

It's because the expressions separated by commas are evaluated before the whole comma-separated tuple (which is an "expression list" in the terminology of the Python grammar). So when you do foo_bar_tuple=="foo", "bar" , that is interpreted as (foo_bar_tuple=="foo"), "bar" . This behavior is described in the documentation .

You can see this if you just write such an expression by itself:

The SyntaxError for the unparenthesized tuple is because an unparenthesized tuple is not an "atom" in the Python grammar, which means it's not valid as the sole content of an if condition. (You can verify this for yourself by tracing around the grammar .)

BrenBarn's user avatar

  • Right! Okay thanks for that mate! I will accept as soon as it will let me :) cheers –  Alex Koukoulas Commented Mar 16, 2014 at 0:37

Considering an example of if 1 == 1,2: which should cause SyntaxError , following the full grammar :

Using the if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] , we get to shift the if keyword and start parsing 1 == 1,2:

For the test rule, only first production matches:

Then we get:

And step down into and_test :

Here we just step into not_test at the moment:

Notice, our input is 1 == 1,2: , thus the first production doesn't match and we check the other one: (1)

Continuing on stepping down (we take the only the first non-terminal as the zero-or-more star requires a terminal we don't have at all in our input):

Now we use the power production:

And shift NUMBER ( 1 in our input) and reduce. Now we are back at (1) with input ==1,2: to parse. == matches comp_op :

So we shift it and reduce, leaving us with input 1,2: (current parsing output is NUMBER comp_op , we need to match expr now). We repeat the process for the left-hand side, going straight to the atom nonterminal and selecting the NUMBER production. Shift and reduce.

Since , does not match any comp_op we reduce the test non-terminal and receive 'if' NUMBER comp_op NUMBER . We need to match else , elif or : now, but we have , so we fail with SyntaxError .

Maciej Gol's user avatar

I think the operator precedence table summarizes this nicely:

You'll see that comparisons come before expressions, which are actually dead last.

Aaron Hall's user avatar

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

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • I'm 14 years old. Can I go to America without my parent?
  • ANOVA with unreliable measure
  • I found a counterexample to one of the intermediate assertions in a proof but not (necessarily) to the overall result – how to publish this?
  • The shortest way from A1 to B1
  • How can I connect my thick wires into an ikea wire connector
  • Probability of visible permutations
  • How does Biden staying in the presidential race hurt Democrats in Congress?
  • Translation of organic compound in classical Chinese
  • Travel in Schengen with French residence permit stolen abroad
  • Did projectiles start being rifled before barrels?
  • Galilean invariance of the wave equation
  • why there is a need to use two access tokens in OpenID Connect?
  • Deleting the comma before the "and" before the final author in a list of authors
  • How to restore a destroyed vampire as a vampire?
  • Generalizations of Hamburger's Theorem
  • How do I distinguish between "e" the natural log base and a variable conventionally referred to as "e"?
  • Libertinus Math with pdfLaTeX?
  • What is Paul trying to say in 1 Corinthians 1:23-24
  • Are foldable tires less puncture resistant
  • How would I translate GPT to German?
  • What's the name of the manga about the student who wakes up as a lake?
  • replacing a 15-amp breaker with a 20-amp breaker
  • Does the universe include everything, or merely everything that exists?
  • Why are the categories of category theory called "category"?

python tuple assignment

IMAGES

  1. Tuple Assignment in Python

    python tuple assignment

  2. Python Tuples and Tuple Methods

    python tuple assignment

  3. Python tuple()

    python tuple assignment

  4. Python Tuple Assignment

    python tuple assignment

  5. Python Tuple Explained with Code Examples

    python tuple assignment

  6. Understanding Tuples In Python

    python tuple assignment

VIDEO

  1. Python Tuple

  2. Python Interactive data sent to List,Tuple,& Dictionary

  3. Tuple in Python?#python #pythonquestions Python #interviewquestions #interviewquestionsandanswers

  4. 2.6 Tuple Assignment in Tamil

  5. 27.Tuple in Python

  6. MODULE-9 PYTHON TUPLE

COMMENTS

  1. Tuple Assignment, Packing, and Unpacking

    00:00 In this video, I'm going to show you tuple assignment through packing and unpacking. A literal tuple containing several items can be assigned to a single object, such as the example object here, t. 00:16 Assigning that packed object to a new tuple, unpacks the individual items into the objects in that new tuple. When unpacking, the number of variables on the left have to match the ...

  2. Tuple Assignment: Introduction, Tuple Packing and Examples

    Learn how to create, access and unpack tuples in python, a data type that is an ordered collection of elements of different data types. See examples of tuple assignment, packing and slicing, and frequently asked questions.

  3. 11.3. Tuple Assignment

    Tuple Assignment — Python for Everybody - Interactive. 11.3. Tuple Assignment ¶. One of the unique syntactic features of Python is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list ...

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

  5. Python Tuple: How to Create, Use, and Convert

    Learn how to create, use, and convert Python tuples, one of the built-in sequence data types. A tuple is immutable, defined by parentheses, and can be unpacked or indexed.

  6. Lists and Tuples in Python

    Learn the basics of lists and tuples, two versatile and useful data types in Python. See how to define, access, modify, and use them in your programs.

  7. Python Tuple (With Examples)

    Learn how to create a tuple by placing items inside parentheses or using a tuple constructor. See how to access tuple items using index numbers and how to check if an item exists in a tuple.

  8. 10.28. Tuple Assignment

    Learn how to use tuple assignment to assign values to multiple variables in one line. See examples of tuple assignment with swapping, matching, and unpacking tuples.

  9. Tuples in Python

    Creating a Tuple. We can create a tuple using the two ways. Using parenthesis (): A tuple is created by enclosing comma-separated items inside rounded brackets. Using a tuple() constructor: Create a tuple by passing the comma-separated items inside the tuple().; Example. A tuple can have items of different data type integer, float, list, string, etc;

  10. 10.3: Tuple Assignment

    10.3: Tuple Assignment. One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list (which is a sequence) and assign the first and ...

  11. Tuples in Python

    Creating Python Tuples. There are various ways by which you can create a tuple in Python. They are as follows: Using round brackets; With one item; ... line 11, in tuple1[1] = 100 TypeError: 'tuple' object does not support item assignment Accessing Values in Python Tuples. Tuples in Python provide two ways by which we can access the elements of ...

  12. 13.3. Tuple Assignment with Unpacking

    13.3. Tuple Assignment with Unpacking ¶. Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

  13. Python Tuple Exercise with solution [10 Exercise Questions]

    Exercise 2: Access value 20 from the tuple. Exercise 3: Create a tuple with single item 50. Exercise 4: Unpack the tuple into 4 variables. Exercise 5: Swap two tuples in Python. Exercise 6: Copy specific elements from one tuple to a new tuple. Exercise 7: Modify the tuple. Exercise 8: Sort a tuple of tuples by 2nd item.

  14. Tuple Assignment Python [With Examples]

    Here are some examples of tuple assignment in Python: Example 1: Basic Tuple Assignment. # Creating a tuple. coordinates = ( 3, 4 ) # Unpacking the tuple into two variables. x, y = coordinates. # Now, x is 3, and y is 4 Code language: Python (python) Example 2: Multiple Variables Assigned at Once. # Creating a tuple.

  15. Python Tuples: A Step-by-Step Tutorial (with 14 Code Examples)

    A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items. Let's take a look at some examples of Python tuples: () — an empty tuple. (1.0, 9.9, 10) — a tuple containing three numeric objects. ('Casey', 'Darin', 'Bella', 'Mehdi') — a tuple containing four string objects.

  16. Python TUPLE

    Tuple Assignment . Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have assigned tuple 1 with the persons information like name, surname, birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).

  17. Python Tuples

    Tuple. Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.. A tuple is a collection which is ordered and unchangeable.. Tuples are written with round brackets.

  18. Python

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  19. python

    Example 1 (Swapping) Tuple assignment can be very handy in order to swap the contents of variables. The following example shows how we can swap the contents of two elements in an array in a clear an concise way without the need of temporary variables:

  20. 5. Data Structures

    Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

  21. Python

    Python tuples are immutable collections of values that can be used to store and manipulate data. In this tutorial, you will learn how to use various tuple methods, such as count, index, and unpacking, to work with tuples in Python. You will also see some examples of how to use tuples in different scenarios. W3Schools is a leading online learning platform that offers free tutorials, references ...

  22. python

    I am trying to change the value of a particular element of a tuple of tuples. Here is the code: y=((2,2),(3,3)) y[1][1]=999 print('y: ',y) TypeError: 'tuple' object does not support item assignment I understand that Tuples are immutable objects. "Immutable" means you cannot change the values inside a tuple. You can only remove them.

  23. 10.3: Tuple Assignment

    10.3: Tuple Assignment. One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list (which is a sequence) and assign the first and ...

  24. Python tuple assignment and checking in conditional statements

    Essentially commas when used in assignments are what actually create tuples, not the parentheses. However, eq operator is a function that takes only single argument, and when you pass it values separated by commas, it takes it as passing arg rather than passing the tuple 'foo','bar'.Wrapping in parens forces the tuple assignment operator to happen before the evaluation of arg, so it behaves as ...