[Go to site: main page, start]

0% found this document useful (0 votes)
8 views9 pages

Python Tuple Methods Explained

The document provides an overview of tuples and sets in Python, highlighting their characteristics and methods. Tuples are immutable sequences that can contain various data types, while sets are mutable collections of unique elements. It also explains how to create sets, perform operations on them, and introduces frozen sets as immutable versions of sets.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Python Tuple Methods Explained

The document provides an overview of tuples and sets in Python, highlighting their characteristics and methods. Tuples are immutable sequences that can contain various data types, while sets are mutable collections of unique elements. It also explains how to create sets, perform operations on them, and introduces frozen sets as immutable versions of sets.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Tuple Methods

Tuple is one of the fundamental data structures in Python, and it is an immutable


sequences. Unlike lists, tuples cannot be modified after creation, making them ideal for
representing fixed collections of data. This immutability play a crucial role in various
scenarios where data stability and security are important. It can contain elements of
different data types, such as integers, floats, strings, or even other tuples.

Python Tuple Methods

The tuple class provides few methods to analyze the data or elements. These methods
allows users to retrieve information about the occurrences of specific items within a tuple
and their respective indices. Since it is immutable, this class doesn't define methods for
adding or removing items. It defines only two methods and these methods provide a
convenient way to analyze tuple data.

Listing All the Tuple Methods

To explore all available methods for tuples, you can utilize the Python dir() function, which
lists all properties and functions related to a class. Additionally, the help() function
provides detailed documentation for each method. Here's an exampl:

Open Compiler

print(dir((1, 2)))
print(help((1, 2).index))

The above code snippet provides a complete list of properties and functions related to the
tuple class. It also demonstrates how to access detailed documentation for a specific
method in your Python environment. Here is the output −

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count',
'index']
Help on built-in function index:

index(value, start=0, stop=9223372036854775807, /) method of [Link] inst ance


Return first index of value.
Raises ValueError if the value is not present.
(END)

Below are the built-in methods for tuples. Let's explore each method's basic functionality −

[Link] Methods & Description

1 [Link](obj)
Returns count of how many times obj occurs in tuple

[Link](obj)
2
Returns the lowest index in tuple that obj appears

Finding the Index of a Tuple Item

The index() method of tuple class returns the index of first occurrence of the given item.

Syntax
[Link](obj)

Return value
The index() method returns an integer, representing the index of the first occurrence of
"obj".

Example
Take a look at the following example −

Open Compiler

tup1 = (25, 12, 10, -21, 10, 100)


print ("Tup1:", tup1)
x = [Link](10)
print ("First index of 10:", x)
It will produce the following output −
Tup1: (25, 12, 10, -21, 10, 100)
First index of 10: 2
Counting Tuple Items

The count() method in tuple class returns the number of times a given object occurs in the
tuple.

Syntax
[Link](obj)

Return Value
Number of occurrence of the object. The count() method returns an integer.

Example
Open Compiler

tup1 = (10, 20, 45, 10, 30, 10, 55)


print ("Tup1:", tup1)
c = [Link](10)
print ("count of 10:", c)
It will produce the following output −
Tup1: (10, 20, 45, 10, 30, 10, 55)
count of 10: 3

Example
Even if the items in the tuple contain expressions, they will be evaluated to obtain the
count.

Open Compiler

tup1 = (10, 20/80, 0.25, 10/40, 30, 10, 55)


print ("Tup1:", tup1)
c = [Link](0.25)
print ("count of 10:", c)
It will produce the following output −
Tup1: (10, 0.25, 0.25, 0.25, 30, 10, 55)
count of 10: 3

Sets
Sets in Python

In Python, a set is an unordered collection of unique elements. Unlike lists or tuples, sets do
not allow duplicate values i.e. each element in a set must be unique. Sets are mutable,
meaning you can add or remove items after a set has been created.

Sets are defined using curly braces {} or the built-in set() function. They are particularly
useful for membership testing, removing duplicates from a sequence, and performing
common mathematical set operations like union, intersection, and difference.
A set refers to a collection of distinct objects. It is used to group objects together and to study their
properties and relationships. The objects in a set are called elements or members of the set.

Creating a Set in Python

Creating a set in Python refers to defining and initializing a collection of unique elements.
This includes specifying the elements that will be part of the set, ensuring that each
element is unique within the set.

You can create a set in Python using curly braces {} or the set() function −

Using Curly Braces


You can directly define a set by listing its elements within curly braces, separating each
element by a comma as shown below −

Open Compiler

my_set = {1, 2, 3, 4, 5}
print (my_set)

It will produce the following result −

{1, 2, 3, 4, 5}

Using the set() Function


Alternatively, you can create a set using the set() function by passing an iterable (like a list
or a tuple) containing the elements you want to include in the set −

Open Compiler

my_set = set([1, 2, 3, 4, 5])


print (my_set)

We get the output as shown below −

{1, 2, 3, 4, 5}

Duplicate Elements in Set

Sets in Python are unordered collections of unique elements. If you try to create a set with
duplicate elements, duplicates will be automatically removed −

Open Compiler

my_set = {1, 2, 2, 3, 3, 4, 5, 5}
print (my_set)

The result obtained is as shown below −

{1, 2, 3, 4, 5}

Sets can contain elements of different data types, including numbers, strings, and even
other sets (as long as they are immutable) −

Open Compiler

mixed_set = {1, 'hello', (1, 2, 3)}


print (mixed_set)

The result produced is as follows −

{1, 'hello', (1, 2, 3)}

In Python, sets support various basic operations that is used to manipulate their elements.
These operations include adding and removing elements, checking membership, and
performing set-specific operations like union, intersection, difference, and symmetric
difference.

Adding Elements in a Set

To add an element to a set, you can use the add() function. This is useful when you want to
include new elements into an existing set. If the element is already present in the set, the
set remains unchanged −

Open Compiler
my_set = {1, 2, 3, 3}
# Adding an element 4 to the set
my_set.add(4)
print (my_set)

Following is the output obtained −

{1, 2, 3, 4}

Removing Elements from a Set

You can remove an element from a set using the remove() function. This is useful when you
want to eliminate specific elements from the set. If the element is not present, a KeyError is
raised −

Open Compiler

my_set = {1, 2, 3, 4}
# Removes the element 3 from the set
my_set.remove(3)
print (my_set)

The output displayed is as shown below −

{1, 2, 4}
Alternatively, you can use the discard() function to remove an element from the set if it is
present. Unlike remove(), discard() does not raise an error if the element is not found in
the set −
Open Compiler

my_set = {1, 2, 3, 4}
# No error even if 5 is not in the set
my_set.discard(5)
print (my_set)

We get the output as shown below −

{1, 2, 3, 4}
Membership Testing in a Set
Sets provide an efficient way to check if an element is present in the set. You can use
the in keyword to perform this check, which returns True if the element is present
and False otherwise −
Open Compiler

my_set = {1, 2, 3, 4}
if 2 in my_set:
print("2 is present in the set")
else:
print("2 is not present in the set")

Following is the output of the above code −

2 is present in the set

Set Operations

In Python, sets support various set operations, which is used to manipulate and compare
sets. These operations include union, intersection, difference, symmetric difference, and
subset testing. Sets are particularly useful when dealing with collections of unique
elements and performing operations based on set theory.

 Union − It combine elements from both sets using the union() function or the | operator.
 Intersection − It is used to get common elements using the intersection() function or
the & operator.
 Difference − It is used to get elements that are in one set but not the other using the
difference() function or the - operator.
 Symmetric Difference − It is used to get elements that are in either of the sets but not in
both using the symmetric_difference() method or the ^ operator.

Python Set Comprehensions

Set comprehensions in Python is a concise way to create sets based on iterable objects,
similar to list comprehensions. It is used to generate sets by applying an expression to each
item in an iterable.

Set comprehensions are useful when you need to create a set from the result of applying
some operation or filtering elements from another iterable.

Syntax
The syntax for set comprehensions is similar to list comprehensions, but instead of square
brackets [ ], you use curly braces { } to denote a set −

set_variable = {expression for item in iterable if condition}

Example
In the following example, we are creating a set containing the squares of numbers from 1 to
5 using a set comprehension −

squared_set = {x**2 for x in range(1, 6)}


print(squared_set)

The output obtained is as follows −

{1, 4, 9, 16, 25}

Filtering Elements Using Set Comprehensions

You can include conditional statements in set comprehensions to filter elements based on
certain criteria. For instance, to create a set of even numbers from 1 to 10, you can use a set
comprehension with an if condition as shown below −

even_set = {x for x in range(1, 11) if x % 2 == 0}


print(even_set)

This will produce the following output −

{2, 4, 6, 8, 10}

Nested Set Comprehensions

Set comprehensions also support nested loops, allowing you to create sets from nested
iterables. This can be useful for generating combinations or permutations of elements.

Example
nested_set = {(x, y) for x in range(1, 3) for y in range(1, 3)}
print(nested_set)

Output of the above code is as shown below −


{(1, 1), (1, 2), (2, 1), (2, 2)}

Frozen Sets

In Python, a frozen set is an immutable collection of unique elements, similar to a regular


set but with the distinction that it cannot be modified after creation. Once created, the
elements within a frozen set cannot be added, removed, or modified, making it a suitable
choice when you need an immutable set.

You can create a frozen set in Python using the frozenset() function by passing an iterable
(such as a list, tuple, or another set) containing the elements you want to include in the
frozen set.

Example
In the following example, we are creating a frozen set of integers and then adding an
element to it −

my_frozen_set = frozenset([1, 2, 3])


print(my_frozen_set)
my_frozen_set.add(4)

Following is the output of the above code −

frozenset({1, 2, 3})
Traceback (most recent call last):
File "/home/cg/root/664b2732e125d/[Link]", line 3, in <module>
my_frozen_set.add(4)
AttributeError: 'frozenset' object has no attribute 'add'

You might also like