Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is Tuple in python?
https://www.programiz.com/python-programming/tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
File name : index.py
mytuple = ("Mahtab", "Sana", "Mahira")
print(mytuple)
Example :-
File name : index.py
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Tuple Packing
A tuple can also be created without using parentheses. This is known as tuple packing.
File name : index.py
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
Output
(3, 4.6, 'dog')
3
4.6
dog
To write a tuple containing a single value you have to include a comma(,) . Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
File name : index.py
tup1 = (50,);
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Output
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Access Tuple Elements
1. Indexing :-
We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 5 elements will have indices from 0 to 4. if you Trying to access an index outside of the tuple index range will raise an IndexError. The index must be an integer, so we cannot use float or other types. This will result in TypeError.
File name : index.py
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
Output
p
t
s
4
2. Negative Indexing:-
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
File name : index.py
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Output
t
p
Slicing :-
We can access a range of items in a tuple by using the slicing operator colon :.
File name : index.py
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])
# elements 8th to end
# Output: ('i', 'z')
print(my_tuple[7:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Output
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Changing a Tuple
tuples are immutable. This means that elements of a tuple cannot be changed once they have been assigned.
File name : index.py
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
concatenation
We can use + operator to combine two tuples. This is called concatenation.
Both + and * operations result in a new tuple.
File name : index.py
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Tuple Length
To determine how many items a tuple has, use the len() function:
File name : index.py
my_tuple = ("Ankita", "Sana", "Mahira")
print(len(my_tuple))
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples
File name : index.py
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
output :
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements
we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.
File name : index.py
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
Tuple Item exists
We can test if an item exists in a tuple or not, using the keyword in.
File name : index.py
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output
True
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each item in a tuple.
File name : index.py
# Using a for loop to iterate through a tuple
for name in ('Sana', 'Mahira'):
print("Hello", name)
Output
Hello Sana
Hello Mahira
Advantages of Tuple over List
File name : index.py
Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:
We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
File name : index.py
File name : index.py
File name : index.py
File name : index.py