Python Tuples for Beginners

Last updated Feb 12, 2021


In this tutorial we are going to learn about the tuples in python in brief. We will cover all the essential topics that will help you master the python tuples. What is tuple? how tuples are used in python? syntax, etc. Let’s get started.

 

In this post  we will cover

  • What is Tuple?
  • Create a Tuple in Python
  • How to access Tuple elements in Python
  • How to Change Tuple in Python
  • How to delete a Tuple in Python

 

 

What is Tuple?

A tuple is just a collection of objects or items which are immutable and ordered. It comes in sequences similar to the list. Tuples cannot be changed but the list can be changed easily. To define tuples in python we are going to use parentheses. Here is the syntax to use tuple in python.

Syntax:

 

tuple_name= ('object1', 'object2', 'object3'........'objectn')

 

Example

tuple1 = ('Bike', 'Car', 2000, 1500)

tuple2 = ('Math', 'Biology', 1952, 1420)

tuple3 = (1, 2, 78, 45)

To define an empty tuple we use.

tuple4 = ();

 

Now let's know about how to create a tuple in a python program.

 

 

Creating the First Tuple in Python

To program our first tuple in python we are going to use the above syntax for initializing the tuple. First, we will create an empty tuple then we will define some values in it. We will change the values to check if it supports different data types or not. Here is the program to get started.

Program:

 

tuple1 = ()

print(tuple1)


# To create a Tuple having integers value

tuple1 = (10, 24, 43)

print(tuple1)


# To create a touple with different datatypes

tuple1 = (1, "Python", 3.4)

print(tuple1)


# To initialize a nested tuple

tuple1 = ("Tuple", [8, 4, 6], (1, 2, 3))

print(tuple1)

 

 

Output:

()                                                                      

 

(10, 24, 43)                                                            

 

(1, 'Python', 3.4)                                                      

 

('Tuple', [8, 4, 6], (1, 2, 3))

 

 

From the above example, it is cleared that tuples accept all data types. We can also define tuples without using parenthesis. Here is an example to explain this statement.

Program:

 

tuple1 = 38, 42.6, "Bike"
print(tuple1)

# Unpacking a tuple is also possible
# It will initialize the tuple values in the following variable
a, b, c = tuple1

print(a) # Output will be 38
print(b) # Output will be 42.6
print(c) # Output will be Bike

 

Output

(38, 42.6, 'Bike')
38
42.6
Bike

 

If you create a tuple with only one element then it will be quite difficult. Having one element within the parenthesis will be considered a string in python. Now we are going to program for tuple that will explain the above statement.

Program:

 

tuple1 = ("Tuple")
# Using type() method to check the type
print(type(tuple1)) # It will print 

# Creating a tuple having only one element
tuple1 = ("Python",)
# Using type() method to check the type
print(type(tuple1)) # It will output the 

# Parentheses are not necessary
tuple1 = "Programming",
# Using type() method to check the type
print(type(tuple1)) # Output will be

 

Output

<class 'str'>                                                           

 

<class 'tuple'>                                                         

 

<class 'tuple'>

 

In the above example, you will observe that we are using an extra comma to define it as a tuple. If you will not use a comma it will be considered as a string so make sure to use an extra comma after defining an element.

 

 

How to access Tuple Elements in Python

Using Indexing

We can easily access any of the tuple elements using index numbers. Basically, we will just get the index number of selected elements and we will use the [] square brackets to access that element.

If a tuple has 6 elements then the index number of the first element will be '0' and of the last element will be '1'. If an index number is not present in a tuple, then it will output an index error. Here is an example to explain this statement

 

# Program to Access a tuple elements in python
tuple1 = ('p','y','t','h','o','n')

# To access element present in index 0 and 5
print(tuple1[0]) # Output will be 'p'
print(tuple1[5]) # Output will be 't'

# If index number is not present it will show an IndexError: list index out of range
# print(my_tuple[6])


# nested tuple
n_tuple1 = ("python", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple1[0][3]) # 's'
print(n_tuple1[1][1]) # 4

 

Output

p
n
h
4

 

 

Using Slicing

The second method to access tuple elements is by using the slicing method. We use this method if we have to access more than one element in a tuple. In python to enable slicing, we use the colon ':' operator. Let's have a look at one example related to slicing.

Program:

 

# Program for accessing tuple elements using slicing method
tuple1 = ('p','y','t','h','o','n','a','b','c')

# To access elements from 2nd to 4th in tuple
# Output will be ('y', 't', 'h')
print(tuple1[1:4])

# To access elements from 0 to 2nd
# Output will be ('p', 'y')
print(tuple1[:-7])

# To access elements from index 8th to end
# Output will be ('b', 'c')
print(tuple1[7:])

# To access elements from beginning to end
# Output will be ('p', 'y', 't', 'h', 'o', 'n', 'a', 'b', 'c')
print(tuple1[:])

 

 

Output

('y', 't', 'h')                                                         

('p', 'y')                                                              

('b', 'c')                                                              

('p', 'y', 't', 'h', 'o', 'n', 'a', 'b', 'c')

 

 

Using Negative Indexing

In python, we can use negative indexing to access elements. The last item in a tuple has an index of '-1' and the second last item has '-2' and so on. Let's check an example to learn negative indexing properly.

Program:

 

# Program for accessing tuple elements using Negative indexing
tuple1 = ('p', 'y', 't', 'h', 'o', 'n')

# Output will be 'n'
print(tuple1[-1])

# Output: 'y'
print(tuple1[-5])

 

Output:

n                                                                      

 

 

How to change a tuple in Python?

Tuples are immutable which means we cannot change tuples once we have assigned them. On the other hand, lists are mutable and can be changed even after assigning them. But we cannot change the tuple after it is initialized. 

 

 

How to Delete a Tuple in Python

As discussed in the above statement, we cannot change a tuple which means that it cannot be deleted. But we can delete an entire tuple by using a del keyword. Let's have a look at its example.

Program:

 

# Program for Deleting entire tuples
tuple1 = ('p', 'y', 't', 'h', 'o', 'n', 'a', 'b', 'c')

# We can't delete items from tuple it will throw an error
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[4]

# We can delete the whole tuple by using del keyword
del tuple1

# Output will be NameError: name 'my_tuple' is not defined
print(tuple1)

 

Output:

Traceback (most recent call last):                                      
 File "main.py", line 12, in                                   
   print(tuple1)                                                       
NameError: name 'tuple1' is not defined 

 

 

Using Iteration Method in Tuple

We can easily use For loop to iterate each item present in the tuple. Here is an example to explain iteration in brief.

Program:

 

for x in ('Python', 'Programming', 'is', 'very', 'easy'):
    print("-", x)

 

Output:

- Python                                                                
- Programming                                                          
- is                                                                    
- very                                                                  
- easy 

 

 

Here we have completed all the essential topics of tuples in python. To master tuples make sure to practice with the coding part. It will help you increase your skills. Here we are sharing some examples which you should practice

 

Example 1:

tup1 = ('Bike', 'Car', 1457, 2021);
tup2 = (14, 24, 33, 24, 35, 76, 47 );
print ("tup1[0]: ", tup1[0]);
print ("tup2[1:5]: ", tup2[1:5]);

 

Output:

tup1[0]:  Bike                                                         
tup2[1:5]:  (24, 33, 24, 35)

 

Example 2:

# Program to create tuple of strings
tuple1 = ("Hello", "Python", "Programmers")
print(tuple1)

# To create a tuple of int, float, string
tuple2 = (10, 12.8, "Hello World")
print(tuple2)

# To create a tuple of string and list
tuple3 = ("Tuple", [10, 20, 30])
print(tuple3)

# To create a tuples inside another tuple
# nested tuple
tuple4 = ((2, 3, 4), (1, 2, "Hello"))
print(tuple4)

 

 

Output:

('Hello', 'Python', 'Programmers')                                      
(10, 12.8, 'Hello World')                                               
('Tuple', [10, 20, 30])                                                 
((2, 3, 4), (1, 2, 'Hello')) 

 

 

Example 3:

 

# To program tuple of strings
tuple1 = ("Cars", "Bike", "Trains")

# To display all elements in tuple
print(tuple1)

# To access first element in tuple
# Output will be "Cars"
print(tuple1[0])

# To access third element in tuple
# Output will be "trains"
print(tuple1[2])

 

Output:

('Cars', 'Bike', 'Trains')                                              
Cars                                                                   
Trains 

 

Related Topics

Python Arrays and Different type of Array Examples

Python Strings - Python String Concatination Examples

Python API Integration


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

197 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions