- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python CGI Programming
- Python Network Programming
- Python Send E-mail
- Python Multi-threading
- Python XML Processing
- Python MySQL Database
- Python GUI Programming
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
Python Tuple
Tuple in Python is a built-in data type, used to store multiple items in a single variable. For example:
x = (120, 42, 350) print(x) x = (12, "codescracker", True, 12.42) print(x)
The output is:
(120, 42, 350) (12, 'codescracker', True, 12.42)
Note - Items of a single tuple can be of multiple types.
Note - Items of a tuple are separated with comma, and the whole items are enclosed within a round brackets or ().
Important - In tuple, items are ordered and unchangeable. Also, tuple items allows duplicates.
Ordered means, indexes assigned to all items when a tuple is created. For example, if a tuple of 5 items is created, then 0 will be the index number of first item, 1 will be the index number of second item, and so on. For example:
x = (12, "codescracker", True, 12.42) print(x[0]) print(x[3])
The output is:
12 12.42
Unchangeable means, we can not change the item of a tuple, after creating it. And two or more items in a tuple can be the same value. For example:
x = (12, "codescracker", True, 12.42, 12, "codescracker", 12) print(x)
The output is:
(12, 'codescracker', True, 12.42, 12, 'codescracker', 12)
Create an Empty Tuple in Python
There are two ways to create an empty tuple in Python. That is, to create an empty tuple, we can use either the tuple() constructor or the round bracket without an item. For example:
x = tuple()
y = ()
Create a Tuple with Items in Python
To create a tuple with items, separate items with comma, and enclose whole items inside a round bracket, and initialize to a variable say a, just like:
a = (2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
Access Items of a Tuple in Python
To access an item of a tuple, here is the syntax:
x[index]
where x refers to the tuple, index refers to the index number of the item, that is going to be accessed. For example:
x = (10, 20, 50, 60)
print(x[2])
The output is:
50
Access Tuple Items using Negative Indexing in Python
The -1 refers to the last index. If there is a tuple named x in your Python program, then x[-1] refers to the last item or element of the tuple, x. For example, the following program prints the last item of a tuple:
mytuple = (12, 43, 65, 76)
print(mytuple[-1])
The output of course will be 76. Negative indexing is sometime useful, when we need to get the last item without using the length of the tuple.
Find Length of a Tuple in Python
Sometime we need to get the length of an anonymous tuple to either iterate the tuple, or to do any specific task. Therefore, Python provides a built-in function named len() that returns the length of a sequence like tuple. For example:
a = (2, 4, 6, 8, 10) print(len(a))
The output is:
5
Must Include a Comma to Create a Tuple with Single Item in Python
To create a tuple in Python that contains single item, a comma after the item needs to be provide to keep it a tuple, instead, a string. For example:
x = ("python",) print(type(x)) x = ("python") print(type(x))
The output is:
<class 'tuple'> <class 'str'>
I think this needs to be fix by the Python's creator. I mean it is too confusing that a tuple with single items must contain a comma to keep it a tuple. But an empty tuple can be created simply using (). I mean, to create either an empty or a multi-items tuple, no extra comma is needed.
Nested Tuple in Python
A tuple can also be used an an item of another tuple. Python allows to nest a tuple inside another. For example:
x = ("Jack", (15, "Dec", 2021), "EECS", "MIT") print(x)
The output is:
('Jack', (15, 'Dec', 2021), 'EECS', 'MIT')
Access Nested Tuple Items in Python
Each and every items of a tuple that are nested inside another tuple, can be accessed individually. That is, the whole tuple that are nested to another tuple, considered as an item.
Therefore the first index will be the whole tuple, and the second index refers to the item number of nested tuple. For example:
x = ("Jack", (15, "Dec", 2021), "EECS", "MIT") print(x[1]) print(x[1][0]) print(x[1][1]) print(x[1][2])
The output is:
(15, 'Dec', 2021) 15 Dec 2021
Tuple Slicing in Python
Items of a tuple can be sliced. The syntax to slice a tuple in Python is:
mytuple[startIndex:stopIndex]
where the startIndex is included and stopIndex is excluded. For example, x[3:7] returns all the items of x, from index number 3 to index number 6. For example:
x = (5, 10, 15, 20, 25, 30, 35, 40, 45, 50)
print(x[3:7])
The output is:
(20, 25, 30, 35)
Tuple Concatenation/addition in Python
To concatenate or add two tuples in Python, use + (plus) operator. For example:
a = (1, 3, 6) b = (2, 3, 8, 12) c = a + b print(c) a = (10, 20, 30) b = (40, 50) a = a + b print(a) a += a print(a) print((1, 2) + (3, 4)) print(("codescracker", True) + ("codes cracker", False))
The output is:
(1, 3, 6, 2, 3, 8, 12) (10, 20, 30, 40, 50) (10, 20, 30, 40, 50, 10, 20, 30, 40, 50) (1, 2, 3, 4) ('codescracker', True, 'codes cracker', False)
Iterating Through a Tuple in Python
We can iterate through a tuple to print all items of a tuple, one by one. For example:
mytuple = (12, 42, "Python", "is", "Fun", 15, True, 12.42) for x in mytuple: print(x)
The output is:
12 42 Python is Fun 15 True 12.42
See how short the code is. Previously, we're using separate print() statement to print each and every items of a tuple, one by one. But now, using a for loop, the whole items of tuple are printed using a single print() statement.
Print Tuple Items in Single Line
The above program can also be modified to print all items of a tuple, in a single line. For example:
mytuple = (15, "Dec", 2021, True, "Today", "Date") for x in mytuple: print(x, end=" ")
Now the output is:
15 Dec 2021 True Today Date
Note - The end= parameter skips the insertion of an automatic newline after print().
We can also create the above program in this way. This program uses the index numbers to print all the items of a tuple, while iterating using for loop:
mytuple = (15, "Dec", 2021, True, "Today", "Date") for i in range(len(mytuple)): print(mytuple[i], end=" ")
You'll get the same output as of above one.
Check Whether an Element is in Tuple or Not in Python
Use the in operator or keyword to check whether a specified element is available in a specified tuple or not. For example, the following program receives a number from user to check whether it is available in the tuple say x or not:
x = (10, 20, 30, 40, 50, 60, 70) print("Enter a Number to Search: ", end="") num = int(input()) if num in x: print("\nThe given value is available in the tuple.") else: print("\nThe given value is not available in the tuple.")
The snapshot given below shows the sample run with user input 30 as number to check:
« Previous Tutorial Next Tutorial »