CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

11 April, 2022

Python Tuple

 Programing Coderfunda     April 11, 2022     Python     No comments   

Python Tuple

Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed.

Creating a tuple

A tuple can be written as the collection of comma-separated (,) values enclosed with the small () brackets. The parentheses are optional but it is good practice to use. A tuple can be defined as follows.

  1. T1 = (101, "Peter", 22)    
  2. T2 = ("Apple", "Banana", "Orange")     
  3. T3 = 10,20,30,40,50  
  4.   
  5. print(type(T1))  
  6. print(type(T2))  
  7. print(type(T3))  

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

Note: The tuple which is created without using parentheses is also known as tuple packing.

An empty tuple can be created as follows.

T4 = ()

Creating a tuple with single element is slightly different. We will need to put comma after the element to declare the tuple.

  1. tup1 = ("JavaTpoint")  
  2. print(type(tup1))  
  3. #Creating a tuple with single element   
  4. tup2 = ("JavaTpoint",)  
  5. print(type(tup2))  

Output:

<class 'str'>
<class 'tuple'>

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index value.

Consider the following example of tuple:

Example - 1

  1. tuple1 = (10, 20, 30, 40, 50, 60)    
  2. print(tuple1)    
  3. count = 0    
  4. for i in tuple1:    
  5.     print("tuple1[%d] = %d"%(count, i))   
  6.     count = count+1  

Output:

(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60

Example - 2

  1. tuple1 = tuple(input("Enter the tuple elements ..."))  
  2. print(tuple1)    
  3. count = 0    
  4. for i in tuple1:    
  5.     print("tuple1[%d] = %s"%(count, i))   
  6.     count = count+1  

Output:

Enter the tuple elements ...123456
('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index value.

We will see all these aspects of tuple in this section of the tutorial.

Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.

Python Tuple

Consider the following example:

  1. tup = (1,2,3,4,5,6,7)  
  2. print(tup[0])  
  3. print(tup[1])  
  4. print(tup[2])  
  5. # It will give the IndexError  
  6. print(tup[8])  

Output:

1
2
3
tuple index out of range

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of tuple that raised an IndexError.

  1. tuple = (1,2,3,4,5,6,7)  
  2. #element 1 to end  
  3. print(tuple[1:])  
  4. #element 0 to 3 element   
  5. print(tuple[:4])  
  6. #element 1 to 4 element  
  7. print(tuple[1:5])   
  8. # element 0 to 6 and take step of 2  
  9. print(tuple[0:6:2])  

Output:

(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

Negative Indexing

The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2 to the second last item and so on.

The elements from left to right are traversed using the negative indexing. Consider the following example:

  1. tuple1 = (1, 2, 3, 4, 5)    
  2. print(tuple1[-1])    
  3. print(tuple1[-4])    
  4. print(tuple1[-3:-1])  
  5. print(tuple1[:-1])  
  6. print(tuple1[-2:])  

Output:

5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)

Deleting Tuple

Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable. To delete an entire tuple, we can use the del keyword with the tuple name.

Consider the following example.

  1. tuple1 = (1, 2, 3, 4, 5, 6)    
  2. print(tuple1)    
  3. del tuple1[0]    
  4. print(tuple1)    
  5. del tuple1    
  6. print(tuple1)    

Output:

(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
  File "tuple.py", line 4, in <module>
    print(tuple1)
NameError: name 'tuple1' is not defined

Basic Tuple operations

The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

OperatorDescriptionExample
RepetitionThe repetition operator enables the tuple elements to be repeated multiple times.
T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
ConcatenationIt concatenates the tuple mentioned on either side of the operator.
T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
MembershipIt returns true if a particular item exists in the tuple otherwise false
print (2 in T1) prints True.
IterationThe for loop is used to iterate over the tuple elements.
for i in T1: 
    print(i)
Output
1
2
3
4
5
LengthIt is used to get the length of the tuple.
len(T1) = 5

Python Tuple inbuilt functions

SNFunctionDescription
1cmp(tuple1, tuple2)It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false.
2len(tuple)It calculates the length of the tuple.
3max(tuple)It returns the maximum element of the tuple
4min(tuple)It returns the minimum element of the tuple.
5tuple(seq)It converts the specified sequence to the tuple.

Where use tuple?

Using tuple instead of list is used in the following scenario.

1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.

2. Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used as a dictionary.

  1. [(101, "John", 22), (102, "Mike", 28),  (103, "Dustin", 30)]  

List vs. Tuple

SNListTuple
1The literal syntax of list is shown by the [].The literal syntax of the tuple is shown by the ().
2The List is mutable.The tuple is immutable.
3The List has the a variable length.The tuple has the fixed length.
4The list provides more functionality than a tuple.The tuple provides less functionality than the list.
5The list is used in the scenario in which we need to store the simple collections with no constraints where the value of the items can be changed.The tuple is used in the cases where we need to store the read-only collections i.e., the value of the items cannot be changed. It can be used as the key inside the dictionary.
6The lists are less memory efficient than a tuple.The tuples are more memory efficient because of its immutability.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Python for loopPython for loopThe for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to tra… Read More
  • Python break statementPython break statementThe break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loop… Read More
  • Python While loopPython While loopThe Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tes… Read More
  • Python LoopsPython LoopsThe flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the prog… Read More
  • Python continue StatementPython continue StatementThe continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement sk… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh
    I had follow these steps to install an configure firebase to my cordova project for cloud messaging. https://medium.com/@felipepucinelli/how...
  • Cashier package and Blade files
    I'm a little confused about this Cashier package. I installed it using the Laravel website (with composer), but noticed there's no...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Auto-translate Application Strings with Laratext - 5/16/2025
  • Simplify Factory Associations with Laravel's UseFactory Attribute - 5/13/2025
  • Improved Installation and Frontend Hooks in Laravel Echo 2.1 - 5/15/2025
  • Filter Model Attributes with Laravel's New except() Method - 5/13/2025
  • Arr::from() Method in Laravel 12.14 - 5/14/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda