Python Tuple

Python Tuple is among the most used data types in Python. In Python, it’s almost unfailing that you must make a sequence of items for programming. In reality, an example is you making a list of what you must purchase when your salary has been paid such as 2 pairs of shoes, a wristwatch, a phone, and 1packet shirt. The python Tuple uses repeated commas(,) to Separate between items. Only that, in Python tuples, the comma-separated items are enclosed in braces().

You might be confused thinking that I mistakenly wrote Tuple in the place of List. The truth is that I am talking about the Python Tuple right now. Although the Python List and Python Tuple are similar in many aspects.

The purpose of this page is to teach you the following:

  • What is Python Tuple?
  • Differences between Python Tuple and Python List
  • Uses of Python Tuple
  • Features (characters) of Python Tuple
  • Examples of Python Tuples

Afterward, I’ll let you put the knowledge to work as I summarize.

What is Python Tuple?

Python Tuple is simply the collection of comma-separated items within parentheses ( ). It enables you to carry out the same operation on multiple values at once, and it’s a great way to keep items in the same category together. A simple example of The Python Tuple is like this: expenses_plan = (‘2pairs of shoes’, ‘a wrist watch’, ‘a phone’, ‘1 packet shirt’).

In other words, Tuple collects multiple items in a single variable. Python Tuples are among the four built-in data types in Python which are List, set, and dictionary. You can create a tuple by using the Tuple() function.

Although by now you’ve got a first glimpse of the difference between Python Tuple and Python List. In complement, let’s see more of their differences.

Differences Between The Python Tuple and Python list

The Python Tuple and python lists are both used to collect comma-separated items enclosed in brackets. However, the first difference between the tuple and the list is the kind of brackets that encloses them. And then other Differences are traceable to when to use a Tuple or a list. Below are some main differences between Tuples and List

  • Bracket Type: The list is enclosed in a box bracket[], while the Tuples are collected in braces().
  • Mutability: The list can be modified after it has been created. Tuples are immutable
  • Concept of Insertion and deletion: List is ideal for insertion and deletion while Tuple is suitable for items accessibility
  • Built-in Functions: List has many built-in functions, Tuples doesn’t have much
  • Unexpected Errors: Unexpected errors easily occur in the list but hardly occur on tuple
  • Iteration: It takes more time to iterate on List, it is is less time consuming to iterate on tuple

Uses Of Python Tuples

The Python Tuple is used for the collection of items sequence enclosed in braces. However, in extension, the python Tuple is used for the following:

  • Used to store multiple items in a single variable
  • Perform similar operation on multiple items at once
  • To collect constant that won’t need modification
  • To make arrays of elements as dictionary keys
  • Similar to list, it’s the easiest way to store data

It’s important to know how python Tuple operates, which takes us to the characters/Features of Tuple.

Python Tuple Characteristics

You must know how Python Tuple behaves and what to expect. Expect the following characters from the Python tuple

  • Tuples are orderly collected
  • Tuples can contain mixed characters like alphabets, numbers, and alphanumerics.
  • Tuple elements are accessible by index.
  • Tuple cannot be formatted after it has been created. Tuples are immutable.

Progressively, let’s look at some of the basic operations in line with the characters of Tuple

Operations On Python Tuples

You’ll be exposed to some major operations with the Python Tuple. But,  before you carry out an operation with the Python Tuple, you have to create a Tuple.

Creating Python Tuple

Creating Python Tuple is as simple as putting comma-separated items in braces ( ). You don’t need any built-in command to achieve Tuple creation, the Tuple() function will do. A Tuple brace or parentheses can be an empty box() or it can hold some numbers, alphabets, or alphanumerics. Note that after Tuple creation, you execute with the print() function.

Example of Tuple creation:

Python Input:

# Python program to demonstrate
# Creation of Tuple
# Creating a Tuple
Tuple = ()
print("Blank Tuple: ")
print(Tuple)
# Creating a Tuple of numbers
Tuple = (10, 20, 14)
print("\nTuple of numbers: ")
print(Tuple)
# Creating a Tuple of strings and accessing
# using index
List = ("Hello", "Dear", "Tanya")
print("\nTuple Items: ")
print(Tuple(0))
print(Tuple(2))
# Creating a Multi-Dimensional Tuple
# (By Nesting a Tuple inside a Tuple)
List = (('Hello', 'Dear'), ('Tanya'))
print("\nMulti-Dimensional Tuple: ")
print(Tuple)

Output:

Blank Tuple:
()
A tuple of numbers:
(10, 20, 14)
List Items
Hello
Tanya
Multi-Dimensional Tuple:
(('Hello', 'Dear'), ('Tanya'))

From the output above, there are four commands

  • The first prints a blank brace bracket because there were no items imputed
  • The second printed out the number s tuple 10, 20, 14
  • The third prints out according to the Tuple index. Note that according to the index method, here a tuple takes an index that is: “Hello”, has the place of “0” and ‘Dear’ has the place of “1” and so on.
  • The last prints out a nested tuple

Now that you’ve learned how tuples can be created, it’s time to know some basic operations on Python tuples.

Accessing Elements in Python Tuple

Tuple elements are simply the indices or the index position of each character in a string literal. The Tuple is a collected string separated with a comma and enclosed in a brace bracket. In Python, indices start from “0” to the next thing “1” and progress in the numeric sequence. You use the index operator() to access an item in a list.

Example

Python Input:

# Accessing tuple elements using indexing
my_tuple = ('pm, 'I, 're, 'm',' i', 't')
print(my_tuple[0])   # 'pm
print(my_tuple[5])   # 'to
# 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

Note: indices must be integers or slices, not float

From the above output, Note that:

  • An index must be an integer (a negative or positive whole number)
  • A slice can be an index
  • Afloat will return an error

Python Tuple: Negative -ve Elements Accessing

Python enables negative indexing or backward indexing, what you should know is that in negative indexing, -1 starts from the first character on the right hand like this:

‘a’,‘b’,‘c’,‘d’,‘e’,
01234
-5-4-3-2-1

Let’s have an example of negative indexing

Python Input:

# Negative indexing in Tuple
my_tuple = (['a',' be,' ca, 'd',' I])
# last item
print(my_tuple[-1])
# fifth last item
print(my_tuple[-5])

Output:

e
a

From the above output,

  • ‘a’ = -5
  • ‘e’ = -1

Python Tuple Slicing

Python Tuple Slicing or Tuple splitting is simply used to build a new Tuple from an existing one. Consequently, python Tuple is splittable. You slice the python Tuple by the Slicicing operator [: ].

Example of Tuple Slicing or splitting in Python

Python Input:

# Tuple slicing in Python
my_Tuple = ('pm,' he, 'o','n', 'I, it's, 'i',' ca,'s')
# elements from index 2 to index 4
print(my_tuple[2:5])
# elements from index 5 to end
print(my_tuple[5:])
# elements beginning to end
print(my_tuple[:])

Output:

('o', 'n', 'e')
('to, 'i', 'c', 's')
('pm,' he, 'o', 'n', 'I, 't', 'i',' ca,'s')

Python Tuple Formatting

Python Tuple unlike List cannot be formatted after it’s been created, this agrees with the fact that Tuple is immutable. However, if the tuple element is a mutable item-like list, then nested items can be modified.

You can re-assign a Tuple to a different value using the Operator/equal to (=)

Python Input:

# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, the 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 = ('pm, 'h', 'o', 'n', 'e', 't', 'i', 'c', 's')
# Output: ('pm, 'h', 'o', 'n', 'e', 't', 'i', 'c', 's')
print(my_tuple)

Output:

(4, 2, 3, [9, 5])
('pm, 'h', 'o', 'n', 'e', 't', 'i', 'c', 's')

Deleting Elements in Python List

You cannot delete a Tuple item once created. However, Python enables you to delete the entire Tuple by using the del() function.

Example:

Python Input:

# Deleting tuples
my_tuple = ('pm, 'h', 'o', 'n', 'e', 't', 'i', 'c', 's')
# 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

Basic Tuples Operations in Python

The table below shows some Python list operators and functions

OperatorDescriptionExample
** RepetitionIt repeats the Tuple elementH*4 = (‘H’, ‘H’, ‘H’, ‘H’,)
ConcatenationIt joins different tuples elements and makes them one(1, 2, 3, 4) + (5, 6, 7, 8) = (1, 2, 3, 4, 5, 6, 7, 8)
in/not in MembershipIt outputs true if an item is among the tuple otherwise false‘r’ in (r, a, t) True
IterationIt uses for loop to iterate over the tuple elementsfor y in (1,2,3): print (y, end = ‘ ‘) = 123
Len() LengthIt’s used to get the length of the tupleLen(12) = 4

Python Tuples Built-in Function

See the table below for the built-in function of the Python tuple

NameFunction
Len(tuple)It gives the total length of the tuple
max(tuple)States items from the tuple with the highest value
min(tuple)States items from the tuple with the least value
Tuple(seq)Changes a list into tuples
CMP(tuple 1,tuple2)Compares Tuple elements

Summary

Python tuple is simply the collection of comma-separated items within parentheses(). It enables you to carry out the same operation on multiple values at once, and it’s a great way to keep items in the same category together. A simple example of The Python tuple is like this: expenses_plan = (‘2 pairs of the shoe’, ‘a wrist watch’, ‘a phone’, ‘1 packet shirt’)

the python Tuple is used for the following:

  • Used to store multiple items in a single variable
  • Perform similar operation on multiple items at once
  • To collect constant that won’t need modification
  • To make arrays of elements as dictionary keys
  • Similar to list, it’s the easiest way to store data

Expect the following characters from the Python tuple

  • Tuples are orderly collected
  • Tuples can contain mixed characters like alphabets, numbers, and alphanumerics.
  • Tuple elements are accessible by index.
  • Tuple cannot be formatted after it has been created. Tuples are immutable.

You also learn the Major operations on the Python Tuple and some built-in functions. I’ve got good news! You can be the best among the pythons today if you’re willing. The secret is to be committed and keep researching until you come out top-notch.

Goodluck Coding!

Hi, I’m Pramod Kumar Yadav & a computer science Engineer with 3years of experience in Digital marketing. I’m self-motivated and love to do SEO.

Leave a Reply

%d bloggers like this: