Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - Tuples

Tuple is an immutable (unchangeable) collection of elements of different data types. It is an ordered collection, so it preserves the order of elements in which they were defined.

Tuples are defined by enclosing elements in parentheses (), separated by a comma. The following declares a tuple type variable.

Example: Tuple Variable Declaration
tpl=() # empty tuple
print(tpl)  #output: ()

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple
print(names)  #output:('Jeff', 'Bill', 'Steve', 'Yash')

nums = (1, 2, 3, 4, 5) # int tuple
print(nums)  #output:(1, 2, 3, 4, 5)

employee=(1, 'Steve', True, 25, 12000)  # heterogeneous data tuple
print(employee)  #output:(1, 'Steve', True, 25, 12000)
Try it

However, it is not necessary to enclose the tuple elements in parentheses. The tuple object can include elements separated by a comma without parentheses.

Example: Tuple Variable Declaration
names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple
print(names)  #output: ('Jeff', 'Bill', 'Steve', 'Yash')

nums = 1, 2, 3, 4, 5 # int tuple
print(nums)  #output: (1, 2, 3, 4, 5)

employee=1, 'Steve', True, 25, 12000  # heterogeneous data tuple
print(employee)  #output: (1, 'Steve', True, 25, 12000)
Try it

Tuples cannot be declared with a single element unless followed by a comma.

Example: Tuple Variable Declaration
names = ('Jeff') # considered as string type
print(names)  #output: 'Jeff'
print(type(names))  #output: <class 'string'>

names = ('Jeff',) # tuple with single element
print(names)  #output: (Jeff)
print(type(names))  #output: <class 'tuple'>
Try it

Access Tuple Elements

Each element in the tuple is accessed by the index in the square brackets []. An index starts with zero and ends with (number of elements - 1), as shown below.

Example: Access Tuple Elements using Indexes
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[0]) #output: 'Jeff'
print(names[1]) #output: 'Bill'
print(names[2]) #output: 'Steve'
print(names[3]) #output: 'Yash'

nums = (1, 2, 3, 4, 5) 
print(nums[0]) #output: 1
print(nums[1]) #output: 2
print(nums[4]) #output: 5
Try it

The tuple supports negative indexing also, the same as list type. The negative index for the first element starts from -number of elements and ends with -1 for the last element.

Example: Negative Indexing
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[-4]) #output: 'Jeff'
print(names[-3]) #output: 'Bill'
print(names[-2]) #output: 'Steve'
print(names[-1]) #output: 'Yash'
Try it

If the element at the specified index does not exist, then the error "index out of range" will be thrown.

s = names[5] #IndexError: tuple index out of range

Tuple elements can be unpacked and assigned to variables, as shown below. However, the number of variables must match with the number of elements in a tuple; otherwise, an error will be thrown.

Example: Access Tuple Elements using Indexes
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
a, b, c, d = names # unpack tuple
print(a, b, c, d)
Try it

Update or Delete Tuple Elements

Tuple is unchangeable. So, once a tuple is created, any operation that seeks to change its contents is not allowed. For instance, trying to modify or delete an element of names tuple will result in an error. However, you can delete an entire tuple using the del keyword.

Example: Update/Delete Tuple
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
names[0] = 'Swati' #throws error
del names[0] #throws error
del names #delete names variable
Try it

Tuple Class

The underlying type of a tuple is the tuple class. Check the type of a variable using the type() function.

Example: Tuple Variable Declaration
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(type(names)) #output: <class 'tuple'>

nums = (1,2,3,4,5) 
print(type(nums))  #output: <class 'tuple'>
Try it

The tuple() constructor is used to convert any iterable to tuple type.

Example: Tuple Variable Declaration
tpl = tuple('Hello')
print(tpl) #output: ('H','e','l','l','o')

tpl = tuple([1,2,3,4,5])
print(tpl) #output: (1,2,3,4,5)

tpl = tuple({1,2,3,4,5}) # converts set to tuple
print(tpl)  #output: (1,2,3,4,5)

tpl = tuple({1:"One",2:"Two"}) # converts dictionary to tuple
print(tpl)  #output: (1,2)
Try it

Tuple Operations

Like string, tuple objects are also a sequence. Hence, the operators used with strings are also available for the tuple.

OperatorExample
The + operator returns a tuple containing all the elements of the first and the second tuple object.
t1=(1,2,3) t2=(4,5,6) print(t1+t2) #(1, 2, 3, 4, 5, 6) t2+(7,)  #(4, 5, 6, 7)
Try it
The * operator Concatenates multiple copies of the same tuple.
t1=(1,2,3) t1*4  #(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
Try it
The [] operator Returns the item at the given index. A negative index counts the position from the right side.
t1=(1,2,3,4,5,6) t1[3] # 4 t1[-2]  #5
Try it
The [:] operator returns the items in the range specified by two index operands separated by the : symbol.
If the first operand is omitted, the range starts from zero. If the second operand is omitted, the range goes up to the end of the tuple.
t1=(1,2,3,4,5,6) t1[1:3] #(2, 3) t1[3:]  #(4, 5, 6) t1[:3]  #(1, 2, 3)
Try it
The in operator returns true if an item exists in the given tuple.
t1=(1,2,3,4,5,6) 5 in t1 #True 10 in t1 #False
Try it
The not in operator returns true if an item does not exist in the given tuple.
t1=(1,2,3,4,5,6) 4 not in t1 #False 10 not in t1 #True
Try it
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.