• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Python Tuples with Examples and Basic Operations on Tuples

  • October 28, 2022
  • CODE OF GEEKS
  • 0
Python Tuples : In this Unit…
  • Python Tuple Basics
  • Python Tuples Immutability Explained
  • Python Tuples Methods
  • Python Nested Tuples


Python Tuples with Examples and Basic Operations on Tuples

A Python Tuple is a sequence which stores a group of elements or items.

Python Tuples are similar to Python Lists but the main difference is tuples are immutable (cannot be modified) whereas lists are mutable (can be modified).

ALSO SEE : Python Tuples Immutability Explained !!

Python Tuples are faster than lists in terms of performance (item lookup). This is because a list is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data) whereas Python tuples requires only single block of memory to store data.

Since Python Tuples are immutable, we can not modify a tuple after creation.

Common methods of Python Lists can not be applied on Python Tuples like append(), extend(), insert(), remove(), pop().

Python Tuple elements are enclosed within ‘( )‘.

Additionally, We can also use tuple() to typecast any iterable object to a list. Like below,

s = "cog" # string
n = {10} # set
l = [4, 5] # list
print(tuple(s)) # string -> tuple
print(tuple(n)) # set -> tuple
print(tuple(l)) # list -> tuple

O/P

(‘c’, ‘o’, ‘g’)
(10,)
(4, 5)

Extra Gyan !!

Tuples in Python can have duplicate values.

Creating a Python Tuple

Tuples can be created by writing elements within parentheses (). Just like Lists, Tuples can also have elements of different types.

t = () # empty tuple
t = (1, ) # tuple with one element, observe ' , ' at the end 
t = (1, 2, 3) # tuple with three element

Please note that t = (10) will be treated as an integer value, whereas t = (10, ) is a tuple.

Additionally, If we do not mention any brackets and write the elements separating them by commas, then, they are considered as tuple, by def.

t = 1, 2, 3
print(type(t)) prints '<class 'tuple'>'

Length of a Python Tuple

Length of a Python Tuple signifies the number of elements in that particular tuple. We can use the len() function to find the length of a tuple.

t = (3, "hello", "nice", 4)
print(len(t)) # prints 4

Indexing in Python Tuples

For tup = (10, “hello”, 30, 50)

Indexing in Python Tuple

Indexing in Python Tuples is same as in Python Lists, starting with 0 to len(tup)-1.

Python Tuples also supports negative indexing, starting from -1 to len(tup). So,

tup[0] will give us 10,
tup[1] will give us “hello”,
Similarly, tup[-2] will give us 30.

Traversing a Python Tuple

Traversal, in simpler words, means to visit each element of the given tuple one by one.

This image has an empty alt attribute; its file name is Screenshot-2022-10-01-151725-1024x369.png
Traversing a Python Tuple

In Python Tuples, traversal can be done in two ways :

1. for loop
2. while loop

Traversing Tuple using for loop

Program : To traverse a given tuple using for loop.

planets = ('mercury', 'venus', 'earth', 'mars')
for each_planet in planets:
    print(each_planet, end=' ')

O/P :

mercury venus earth mars

Here, variable ‘each_planet’ is acting as a tuple element (iterator).

We can also iterate over a given sequence using range() function within the for loop.

Extra Gyan !

range() function in Python is used to generate a sequence or series of numbers, starting from 0, ending just before the given limit and increments by 1. These are the default values which can be changed as per the requirements.

Syntax

range(start, end+1, step_size)

start : This signifies the starting point of the sequence.

end : This signifies the ending point of the sequence.

step_size : This signifies the value with which each digit of sequence will either increase or decrease.

Like, in series 2, 4, 6, 8, we have two as a step size.

Below are the different ways in which range() function can be used :

1. range(n) : We will use this when we want to generate a sequence of numbers from 0 to n-1, keeping 1 as step size.

2. range(0, 10) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 1 as step size.

3. range(0, 10, 2) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 2 as step size. This series will be as ‘0, 2, 4, 6, 8’.

4. range(10, 0, -1) : We will use this when we want to generate a sequence of numbers from 10 to 1,

Program : To traverse a given tuple using for loop (range).

planets = ('mercury', 'venus', 'earth', 'mars')
for i in range(0, len(planets)):
    print(planets[i], end=' ')
print()
# reverse order
for i in range(len(planets)-1, -1, -1):
    print(planets[i], end=' ')
print()
# reverse using negative indexing
for i in range(-1, -(len(planets))-1, -1): # loop will run for index -1 to -4
    print(planets[i], end=' ')

O/P :

mercury venus earth mars
mars earth venus mercury
mars earth venus mercury

We all know that just like lists, Python Tuples are indexable too. In the above program, we were able to access each element of the given tuple with its index using range() function.

Consider line-3 of code

for i in range(0, len(planets)):

This for loop will run ‘len(planets)’ times, starting from i = 0 and ending at i = len(planets) – 1.

Variable ‘i‘ holds integer value.

Here, in our program, len(planets) = 4

Hence, this for loop will run four times, starting from 0 and ending to 3.

Traversing tuple using while loop

Program : To traverse a given tuple using while loop.

planets = ('mercury', 'venus', 'earth', 'mars')
i = 0
while i < len(planets):
  print(planets[i], end= ' ')
  i+=1
print()
# reverse order
j = len(planets)-1
while j >= 0:
  print(planets[j], end= ' ')
  j-=1

O/P :

mercury venus earth mars
mars earth venus mercury

Slicing in Python Tuples

Slicing refers to the process of extracting a piece or part of the tuple following 0-based indexing. Slicing is typically done in the following format

tuple[start: stop: stepsize]

Here, ‘start’ represents the position of starting element of the tuple, ‘stop’ represents the position of ending element of the tuple and ‘stepsize’ indicates the increment/ decrement.

For a tuple of ‘n‘ elements, default value for ‘start’ will be 0, ‘end’ will be (n-1), ‘stepsize’ will be 1.

Let’s see different slicing ways for ‘+’ stepsize

tuple = (1, 2, 3, 4, 5) 
print(tuple[:]) # prints all elements of tuple i.e 1, 2, 3, 4, 5
print(tuple[1:4]) # prints all elements from position 1 to position 3 (4-1) i.e 2, 3, 4
print(tuple[::2]) # here, start = 0, end = 4 (5-1), prints elements from position 0 to position 4, keeping stepsize as 2, i.e 1, 3, 5
print(tuple[1::]) # here, start = 1, end = 4, prints elements from position 1 to position 4 i.e 2, 3, 4, 5

For ‘-‘ stepsize

If the stepsize is negative then elements are extracted in reverse order (following 1-based indexing), rest everything remains same.

tuple = (1, 2, 3, 4, 5) 
print(tuple[::-2]) # prints 5, 3, 1 as stepsize is 2 and '-' sign indicates reverse order

When the stepsize is positive, then elements are extracted from left to right, whereas in case of negative stepsize, elements are extracted from right to left.

tuple = (1, 2, 3, 4, 5) 
print(tuple[-4:-1]) # prints 2, 3, 4 

In the above code, start is ‘-4’ which is the fourth element from right, elements are extracted from position ‘start’ to ‘end – 1’, hence, from -4 to -2.

Find the O/P for t = (3, 4, 6, 12, 5, 10)

print(t[2:5])

Ans. (6, 12, 5)

print(t[3::2])

Ans. (12, 10)

print(t[4:5:1])

Ans. (5,)

print(t[2:4:-1])

Ans. ()

print(t[-2:-4:-1])

Ans. (5, 12)

print(t[::-4])

Ans. (10, 4)



Taking tuple as an Input

We can use input() method to take input from the user, which can be later type-casted to tuple.

s = tuple(input('Enter your tuple : ')) 
print("tuple is : ",s)

O/P

Enter your tuple : 3412
tuple is : (‘3’, ‘4’, ‘1’, ‘2’)

We can also use eval() function to evaluate whether typed elements are a list or a tuple.

s = eval(input('Enter your tuple : ')) 
print("tuple is : ",s)

Concatenation of Python Tuples

Concatenation refers to the process of attaching two or more tuples to form a resultant tuple.

We can simple use ‘+’ operator to perform tuple concatenation.

inner_planets = ('mercury', 'venus', 'earth', 'mars') # tuple1
outer_planets = ('jupiter', 'saturn', 'uranus', 'neptune') # tuple2
planets = inner_planets + outer_planets # concatenating two tuples
print("All Planets : ", planets)

O/P

All Planets : (‘mercury’, ‘venus’, ‘earth’, ‘mars’, ‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’)



Repetition of Tuples

Repetition refers to the process of repeating the elements of a tuple ‘n’ number of times.

We can simple use ‘*’ operator to perform tuple repetition.

If we write, t*n, then it means tuple l will be repeated n number of times.

t = (2, 4, 6)
print(t * 3)

O/P

(2, 4, 6, 2, 4, 6, 2, 4, 6)

Here, tuple l, is repeated thrice as specified.

Membership in Python Tuples

Suppose if we want to check whether a given element (or a subtuple) is a member of the given tuple.

This can be done using in and not in operator in Python.

If the element is the member of the tuple, then, in operator returns True, else False.

If the element is not the member of the tuple, then, not in operator returns True, else False.

t = (1, 2, 3, 4, 5)
item = 10 
print(item in t) # checking for 10 in given tuple, returns False
print(item not in t) # returns True

O/P

False
True





  • Previous Python Tuples Immutability Explained !!
  • Next List Comprehensions in Python

Leave a Reply Cancel reply

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

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.