Python Tuples- Immutable Date in Python
Python Tuples - Store Data That Cannot Change
Introduction
In Python, we learned about lists, which allow us to store multiple values in a single variable and modify them later.
But sometimes we need data that should not change during the program.
For this purpose, Python provides Tuples.
Tuples are similar to lists, but they are immutable, which means their values cannot be changed after creation.
What Is a Tuple?
A tuple is a collection of items separated by commas stored inside parentheses( ). It is immutable.
Example:
numbers = (10, 20, 30,40)
print(numbers)
Output:
(10, 20, 30, 40)
Tuple Can Store Different Data Types
Just like lists, tuples can store different types of data
Example:
data =("Python", 21, 85.5, True)
print(data)
A tuple can store:
- Strings
- Integers
- Floats
- Boolean values
Creating Tuples
To create a tuple put a number of expressions, separated by commas in parentheses. You can write in the form given below:
T= ( )
T=(value,)
Create a Empty Tuple
The empty tuple is (). You can also create empty tuple as:
T=tuple()
Create a Single Element Tuple
While creating Single element tuple always remember, if you just give a single element in a round brackets, Python consider it a value only, for example:
t=(1)
print(t)
Output:
1
To construct a tuple with one element just add a comma after the single element as shown below:
t=3,
print(t)
Output:
(3,)
Creating Tuples from Existing Sequence
You can also create a tuple using built-in tuple type to create tuples from sequence as per the syntax given below:
T= tuple(<sequence>)
Consider the following examples:
t1=tuple("hello")
print(t1)
Output:
('h', 'e', 'l', 'l', 'o')
You can also create a list from user input as follows:
Code:
t1=tuple(input("Enter tuple elements:"))
print(t1)
Output:
Enter tuple elements: 23456
("2", "3", "4", "5", "6")
Accessing Tuple Elements(Indexing)
Tuple elements are accessed using positive as well as negative indexing, just like lists. For example:
fruits = ("Apple", "Banana", "Mango")
print(fruits[0])
Output:
Apple
You can also access elements from the end using negative indexing by:
print(fruits[-1])
Output:
Mango
Looping Through a Tuple
You can use a loop to access each element. For example, following loop shows each item of a tuple T in separate lines:
fruits = ("Apple", "Banana", "Mango")
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Mango
Finding Length of Tuple
We can find out the length of the tuple by using len() function. For example:
numbers = ( 10, 20, 30, 40)
print(len(numbers))
Output:
4
Practice Questions
- Create a tuple with 5 numbers.
- Print the second element of a tuple.
- Find the length of a tuple.
- Print all elements using a loop.
- Create a tuple of student names.
Comments
Post a Comment