Skip to main content

Python Tuple | PythonHub

 Python Tuple


In Python programming, a tuple 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 in a list, elements can be changed.

Advantages of Tuple over List

Since, tuples are quite similiar to lists, both of them are used in similar situations as well. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:
  • We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.
  • Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
  • Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
  • If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.



Creating a Tuple

A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it. A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)

# tuple having integers
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

# tuple can be created without parentheses
# also called tuple packing
# Output: 3, 4.6, "dog"

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

# tuple unpacking is also possible
# Output:
# 3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'dog')
3
4.6
dog
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.
# only parentheses is not enough
# Output: 
my_tuple = ("hello")
print(type(my_tuple))

# need a comma at the end
# Output: 
my_tuple = ("hello",)  
print(type(my_tuple))

# parentheses is optional
# Output: 
my_tuple = "hello",
print(type(my_tuple))
output



Changing a Tuple

Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])

# we cannot change an element
# If you uncomment line 8
# you will get an error:
# TypeError: 'tuple' object does not support item assignment

#my_tuple[1] = 9

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

# tuples can be reassigned
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple)



We can use + operator to combine two tuples. This is also called concatenation. We can also repeat the elements in a tuple for a given number of times using the * operator. Both + and * operations result into 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)

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple. But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items
# if you uncomment line 8,
# you will get an error:
# TypeError: 'tuple' object doesn't support item deletion

#del my_tuple[3]

# can delete entire tuple
# NameError: name 'my_tuple' is not defined
del my_tuple
my_tuple

Python Tuple Methods

Methods that add items or remove items are not available with tuple. Only the following two methods are available.
Python Tuple Method
MethodDescription
count(x)Return the number of items that is equal to x
index(x)Return index of first item that is equal to x
my_tuple = ('a','p','p','l','e',)

# Count
# Output: 2
print(my_tuple.count('p'))

# Index
# Output: 3
print(my_tuple.index('l'))



Other Tuple Operations 1. Tuple Membership Test

We can test if an item exists in a tuple or not, using the keyword in.
my_tuple = ('a','p','p','l','e',)

# In operation
# Output: True
print('a' in my_tuple)

# Output: False
print('b' in my_tuple)

# Not in operation
# Output: True
print('g' not in my_tuple)

2. Iterating Through a Tuple

Using a for loop we can iterate though each item in a tuple.
# Output: 
# Hello John
# Hello Kate
for name in ('John','Kate'):
     print("Hello",name) 

Built-in Functions with Tuple

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), tuple() etc. are commonly used with tuple to perform different tasks.
Built-in Functions with Tuple
FunctionDescription
all()Return True if all elements of the tuple are true (or if the tuple is empty).
any()Return True if any element of the tuple is true. If the tuple is empty, return False.
enumerate()Return an enumerate object. It contains the index and value of all the items of tuple as pairs.
len()Return the length (the number of items) in the tuple.
max()Return the largest item in the tuple.
min()Return the smallest item in the tuple
sorted()Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum()Retrun the sum of all elements in the tuple.
tuple()Convert an iterable (list, string, set, dictionary) to a tuple.

Accessing Elements in a Tuple

There are various ways in which we can access the elements of a tuple.

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 6 elements will have index from 0 to 5. Trying to access an element other that (6, 7,...) will raise an IndexError. The index must be an integer, so we cannot use float or other types. This will result into TypeError. Likewise, nested tuple are accessed using nested indexing, as shown in the example below.
my_tuple = ['p','e','r','m','i','t']

# Output: 'p'
print(my_tuple[0])

# Output: 't'
print(my_tuple[5])

# index must be in range
# If you uncomment line 14,
# you will get an error.
# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer
# If you uncomment line 21,
# you will get an error.
# 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
# Output: 's'
print(n_tuple[0][3])

# nested index
# Output: 4
print(n_tuple[1][1])

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.
my_tuple = ['p','e','r','m','i','t']

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

Ref: Learn python:Python tutorial app

App by Avrram piperidas

Most Popular Course:Data Science of Harvard, MIT, IBM.... 

John Academy: 97% Off on Popular Online Courses



Amazon Best Seller in Baby Products

2. Slicing

We can access a range of items in a tuple by using the slicing operator - colon ":".
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[:])

Comments

Popular posts from this blog

Python Input and Output | Usage of input and output

  Python Output Using print() function We use the print() function to output data to the standard output device (screen). print('This sentence is output to the screen') # Output: This sentence is output to the screen a = 5 print('The value of a is', a) # Output: The value of a is 5 output This sentence is output to the screen The value of a is 5 In the second print() statement, we can notice that a space was added between the string and the value of variable a.This is by default, but we can change it. The actual syntax of the print() function is print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout (screen). Here are an example to illustrate this. Amazon Best...

Python Package

  Python Package We don't usually store all of our files in our computer in the same location. We use a well-organized hierarchy of directories for easier access. Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. Analogous to this, Python has packages for directories and modules for files. As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. This makes a project (program) easy to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules. A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file. Importing module from a package We can import modules from packages using the dot (....

Learn python:usage of if...else Statement.

Python if...else Statement Decision making is required when we want to execute a code only if a certain condition is satisfied. The if…elif…else statement is used in Python for decision making. Python if Statement Syntax if test expression: statement(s) Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True. If the text expression is False, the statement(s) is not executed. In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True. None and 0 are interpreted as False. Example: Python if Statement # If the number is positive, we print an appropriate message num = 3 if num > 0 : print(num, "is a positive number." ) print( "This is always printed." ) num = -1 if num > 0 : print(num, "is a positive number." ) print( "This is also always pri...