Python Tuples

Python has 4 built-in data types that are used to store collections of data, They are  Python Tuples

  1. List
  2. Tuple
  3. Set
  4. Dictionary

In this tutorial we will learn about Lists.

Tuples have a collection of elements which is ordered and unchangeable (immutable). It allows duplicate members. While List is a collection which is ordered and changeable. It allows duplicate members.

Creating a Tuple

my_tuple = ()
print(my_tuple)

Example

list_numbers = [1, 2, 3, 4, 5]
tuple_numbers = (1, 2, 3, 4, 5)

print(list_numbers)
print(tuple_numbers)


#type() function is used check the type of data structure
print(type(list_numbers)) 
print(type(tuple_numbers))
[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)
<class 'list'>
<class 'tuple'>

1. Accessing in Tuples:

Accessing in tuples is also pretty similar to that in lists, the first element has index zero, and it keeps on increasing for the next consecutive elements. Also, backward indexing is also valid in tuples.

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

print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])
1
2
3

2. Adding Elements to a Tuple:

As we know, that tuples are immutable, hence the data stored in a tuple cannot be edited, but it’s definitely possible to add more data to a tuple. This can be done using the addition operator.

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

my_tuple = my_tuple + (6,)
print(my_tuple)
(1, 2, 3, 4, 5, 6)

3. Deleting a Tuple:

In order to delete a tuple, the del keyword is used.

my_tuple = (1, 2, 3, 4, 5)
del (my_tuple)

print(my_tuple)
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(my_tuple)
NameError: name 'my_tuple' is not defined

Once we delete the tuple it will no longer available.

4. Slicing in Tuples:

Slicing in tuples works exactly the same as in the case of lists.

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[2:4])
(3, 4)

Difference between list and tuple

ListsTuples
Mutable (can be modified)Immutable (cannot be modified)
Created with square brackets []Created with round parentheses () or the tuple() function
Can contain multiple data typesCan contain multiple data types
Can be used as an argument in functions that modify the list (e.g. list.append())Can be used as a key in a dictionary

Python Tuples
  1. Tuples have a collection of elements which is ordered and unchangeable (immutable). It allows duplicate members.