in , ,

Python Tuple

python tuple

Python tuple: In this tutorial, you’ll learn everything about Python tuples. more specifically, what are tuples, how to make them, when to use them, and different methods you should be familiar with?

A tuple in Python is similar to a list. The difference between the two is that we can’t change the components of a tuple once it is assigned whereas we can change the elements of a list.


In this article, you will learn-

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.).

# 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))

A tuple can also be created without using parentheses. This is known as tuple packing.

my_tuple = 3, 4.6, "orange"
print(my_tuple)

# tuple unpacking is also possible
a, b, c = my_tuple

print(a)      # 3
print(b)      # 4.6
print(c)      # orange

Output

(3, 4.6, 'orange')
3
4.6
orange

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a

trailing comma to indicate that it is, in fact, a tuple.

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

There are different manners by which we can get to the components of a tuple.

1. Indexing

We can use the index operator  [] to access an item in a tuple, where the list begins from 0.

Along these lines, a tuple having 6 components will have lists from 0 to 5. Attempting to get to a list outside of the tuple list range(6,7,… in this model) will raise an IndexError.

The index must be an integer, so we can’t use float or other sorts. This will result in TypeError.

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

# 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.

# 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

3. Slicing

We can access a range of items in a tuple by using the slicing operator colon.

# Accessing tuple elements using slicing
my_tuple = ('w','o','r','l','d','o','f','i','t','e','c','h')

# elements 2nd to 4th
# Output: ('o', 'r', 'l')
print(my_tuple[1:4])

# elements beginning to 2nd
# Output: ('w', 'o')
print(my_tuple[:-7])

# elements 8th to end
# Output: ('c', 'h')
print(my_tuple[7:])

# elements beginning to end
# Output: ('w','o','r','l','d','o','f','i','t','e','c','h')
print(my_tuple[:])
Output
('o', 'r', 'l')
('w', 'o')
('c', 'h')
('w', 'o', 'r', 'l', 'd', 'o', 'f', 'i', 't', 'e', 'c', 'h')

Changing a Tuple

Unlike lists, tuples are immutable.

This means that elements of a tuple can’t be changed once they have been appointed. Be that as it may, if the component is itself an alterable information type like list, its nested items can be changed.

We can also assign a tuple to different values (reassignment).

# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])


# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9

# However, item of mutable element can be changed
my_tuple[3][0] = 9    # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned
my_tuple = ('w','o','r','l','d','o','f','i','t','e','c','h')

# Output: ('w', 'o', 'r', 'l', 'd', 'o', 'f', 'i', 't', 'e', 'c', 'h')
print(my_tuple)

Output

(4, 2, 3, [9, 5])
('w', 'o', 'r', 'l', 'd', 'o', 'f', 'i', 't', 'e', 'c', 'h')

We can use + operator to combine two tuples. This is called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result in a new tuple.

# 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')

Deleting a Tuple

As discussed above, we can’t change the components in a tuple. It implies that we can’t erase or expel things from a tuple.

Deleting a tuple entirely, however, is possible using the keyword del.

# Deleting tuples
my_tuple = ('w','o','r','l','d','o','f','i','t','e','c','h')

# 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)

Output

Traceback (most recent call last):
  File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined


Tuple Methods

Methods that include things or evacuate things are not available with a tuple. Just the accompanying two techniques are accessible.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p'))  # Output: 2
print(my_tuple.index('l'))  # Output: 3

Output

2
3

Other Tuple Operations

1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.

# 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

2. Iterating Through a Tuple

We can use a for loop to iterate through each item in a tuple.

# Using a for loop to iterate through a tuple
for name in ('salman', 'khan'):
    print("Hello", name)
Otput
Hello salman
Hello khan

Advantages of Tuple over List

Since tuples are very like records, the two are used in similar situations. Be that as it may, there are sure favorable circumstances of executing a tuple over a rundown. Beneath recorded are a portion of the principle favorable circumstances:

We generally use tuples for heterogeneous (unique) information types and records for homogeneous (comparative) information types.

Since tuples are permanent, emphasizing through a tuple is quicker than with a list. So there is slight exhibition support.

Tuples that contain unchanging components can be utilized as a key for a word reference. With records, this is unimaginable.

If you have data that doesn’t change, actualizing it as a tuple will ensure that it remains write-protected.


Please feel free to give your comment if you face any difficulty here.

For More Latest Articles Click on Below Link.

https://www.worldofitech.com/python-data-types/

salman khan

Written by worldofitech

Leave a Reply

python list

Python List

Python Strings

Python Strings