Tuples are an ordered and immutable sequence of items, often used to store multiple items as a single unit. Tuples are defined by enclosing elements within parentheses ( ). Tuples can contain items of any type and can have duplicates. The items in a tuple can be accessed using indexing and slicing, just like lists.
Some common operations on tuples include concatenation, repetition, membership testing, and iteration. Unlike lists, tuples are fixed in size, and their items cannot
be modified.
Creating Tuples
A tuple is created by enclosing a comma-separated sequence of values within round parentheses “()”.
For example:
Creating a tuple with values
my_tuple = (1, 2, 3, 4)
Creating a tuple with single value
my_tuple = (1,)
Note the comma after the value, Tuples can also be created using the built-in function tuple(), by passing a sequence as an argument.
Creating a tuple from a list
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
The values in a tuple are immutable, i.e., once created, they cannot be modified.
Operation on Tuples
Tuples in Python are immutable, meaning their elements cannot be changed once defined. Some operations that can be performed on tuples include:
Accessing elements: Tuples can be accessed like lists using indices.
Slicing: Like lists, tuples can be sliced to return a portion of the original tuple.
Concatenation: Tuples can be concatenated with the + operator.
Length: The length of a tuple can be found using the len() function.
Membership testing: The in and not in operators can be used to check if an element is present in a tuple.
Comparison: Tuples can be compared to other tuples, and return True or False based on lexicographic order.
Nesting: Tuples can contain elements of any type, including other tuples.
Accessing of elements from Tuples
Tuples elements can be accessed in the same way as lists, by using indices. However, unlike lists, tuples are immutable, which means you cannot modify their contents once they are created. Here’s an example of accessing elements in a tuple:
Slicing of Tuples
Slicing of Tuples is similar to the slicing of Lists in python programming. In slicing, we extract a portion of the Tuple based on the start and end indices.
The syntax for slicing is as follows:
tuple_name[start_index:end_index:step]
where tuple_name is the name of the Tuple, start_index is the starting index from where the slice starts, end_index is the ending index till where the slice ends (not inclusive), and step is the increment between consecutive elements in the slice (optional).
Example:
Membership Testing of Tuples
Membership testing in tuple is a process of checking if a specific element exists in the tuple or not. This can be done using the in operator. The in operator returns True if the element exists in the tuple and False if it does not.
Here’s an example:
Built-in functions on tuples
There are several built-in functions in Python that can be used on tuples:
len(tuple): returns the number of elements in the tuple
max(tuple): returns the largest item in the tuple
min(tuple): returns the smallest item in the tuple
tuple(sequence): returns a tuple from a given sequence, such as a list
sorted(tuple): returns a sorted version of the tuple
sum(tuple): returns the sum of all elements in the tuple
all(tuple): returns True if all elements in the tuple are true, and False otherwise
any(tuple): returns True if any elements in the tuple are true, and False otherwise
len(tuple)
len(tuple) returns the number of elements in a tuple.
For example:
max(tuple)
The max function in Python can be used to find the maximum value in a tuple.
Example:
numbers = (1, 2, 3, 4, 5)
max(numbers) #Output: 5
min(tuple)
The min function returns the minimum value in a tuple.
For example:
t = (1, 2, 3, 4, 5)
min(t) #Output: 1
If the tuple contains elements of different types, an error will occur. The elements of the tuple must be comparable to each other.
tuple(sequence)
The tuple(sequence) function in Python is used to convert a sequence (such as a list, string, etc.) into a tuple. The converted tuple will have the same elements as the original sequence, in the same order.
Example:
sorted(tuple)
The sorted function returns a new sorted list object, sorted in ascending order, from the elements of a tuple. The original tuple remains unchanged.
For example:
sum(tuple)
The built-in function sum(tuple) in Python programming adds all the elements in the given tuple. It takes a tuple as argument and returns the sum of all its elements. The elements in the tuple must be numerical.
Here’s an example:
all(tuple)
all(tuple) is a built-in function in Python that returns True if all elements of the tuple are true (or if the tuple is empty).
A value is considered “true” if it evaluates to True in a boolean context.
For example, the following values are considered true:
numbers other than 0 (e.g. 1, 2, 3)
any non-empty string or list
And the following values are considered false:
0
an empty string or list
None
So, if all elements of the tuple are true, all(tuple) returns True. Otherwise, it returns False.
For example:
numbers = (1, 2, 3)
all(numbers)
True
numbers = (0, 1, 2)
all(numbers)
False
all(tuple)
all(tuple) is a built-in function in Python that returns True if all elements in the given iterable (in this case a tuple) are true (i.e., not False or None), and False otherwise.
Example:
t = (1, 2, 3, 4)
all(t)
True
t = (1, 2, 3, 0)
all(t)
False
any(tuple)
The “any” function in Python returns True if at least one element in the tuple is truthy (i.e., evaluates to True). If all elements in the tuple are false (i.e., evaluate to False), it returns False.
Example:
numbers = (0, 0, 0, 0)
any(numbers)
False
numbers = (0, 1, 0, 0)
any(numbers)
True
Sets
A set is an unordered collection of unique elements in Python. It is defined with curly braces {} or the built-in set() function. The elements of a set can be of any hashable data type, including numbers, strings, and tuples. Unlike lists and tuples, sets do not maintain any order and do not support indexing or slicing.
Example:
Creations of Sets
Sets in Python can be created using the set() constructor or by enclosing elements within curly braces {}. The elements in a set must be unique and can be of any data type, including numbers, strings, and other data structures like lists and dictionaries.
Examples:
Operations on sets
Sets in Python are used to perform mathematical operations like union, intersection, difference and symmetric difference.
Here are the common operations:
Union: This operation returns a set that contains all the elements from both the sets. It is performed using the union() method or the ‘|’ operator.
Intersection: This operation returns a set that contains the common elements of both sets. It is performed using the intersection() method or the ‘&’ operator.
Difference: This operation returns a set that contains elements present in the first set but not in the second set. It is performed using the difference() method or the ‘-’ operator.
Symmetric Difference: This operation returns a set that contains elements present in either set but not in both. It is performed using the symmetric_difference() method or the ‘^’ operator.
Subset: This operation returns True if all elements of one set are present in the other set. It is performed using the issubset() method.
Superset: This operation returns True if the other set is a subset of the first set. It is performed using the issuperset() method.
Built-In Functions on Sets
Python provides several built-in functions for sets, some of them are:
len(set) : Returns the number of elements in the set.
max(set) : Returns the largest element in the set.
min(set) : Returns the smallest element in the set.
sorted(set) : Returns a sorted list of elements in the set.
sum(set) : Returns the sum of elements in the set.
all(set) : Returns True if all elements in the set are True, otherwise False.
any(set) : Returns True if any element in the set is True, otherwise False.
set(iterable) : Converts an iterable object (list, tuple, etc.) into a set.
frozenset(iterable) : Converts an iterable object into an immutable set.
len(set)
The len() function returns the number of elements in a set.
Example:
max(set)
The max() function returns the largest item in an iterable or the largest of two or more arguments. When used with a set, it returns the item with the highest value in the set, according to the elements’ ordering. Note that sets are unordered collections, so the result of max() is not guaranteed to be consistent between different runs of the same code.
Example:
set1 = {1, 2, 3, 4, 5}
max(set1)
#Output: 5
min(set)
The min() function returns the smallest element in a set. The set must be non-empty and its elements must be comparable(e.g., numbers or strings).
Here’s an example:
set1 = {1, 3, 5}
min(set1)
#Output: 1
sorted(set)
The sorted() function returns a sorted list of the elements in a set. It sorts the elements in ascending order by default.
Example:
sum(set)
The sum function in Python can be applied to sets, but it is important to note that sets are unordered and do not contain duplicate elements, so summing a set doesn’t make much sense. The function sum can only be applied to an iterable of numbers, such as a list or tuple, not a set.
Example:
all(set)
The all(set) function returns True if all elements in the set are truthy (i.e., not equal to False or None), and False otherwise. If the set is empty, it returns True.
Example:
any(set)
The any built-in function in Python returns True if at least one element of the input iterable (e.g. set) is truthy, and False otherwise.
Example:
set1 = {0, 2, 3, 4}
any(set1)
True
set2 = {0, False}
any(set2) #Output:False
set(iterable)
set(iterable) is a built-in function in Python that creates a set from an iterable object such as a list or a string. It returns a set object that contains unique elements from the iterable object.
Example:
frozenset(iterable)
frozenset is a built-in function in Python that returns an immutable version of a set. The elements of the iterable passed to frozenset are the elements of the frozen set.
Syntax: frozenset(iterable)
Example:
fs = frozenset([1, 2, 3, 4, 5])
fs
frozenset({1, 2, 3, 4, 5})
fs[0] = 10
AttributeError: ‘frozenset’ object has no attribute ‘_ setitem_’
Note: Since frozen sets are immutable, we can’t modify their elements after creation.
Set Methods
In Python programming, sets have several built-in methods.
Some of the commonly used ones include:
add() – adds an element to the set.
clear() – removes all elements from the set.
copy() – returns a shallow copy of the set.
difference() – returns the difference between two sets as a new set.
difference_update() – removes the items in the set that exist in another set.
discard() – removes an element from the set if it is present.
intersection() – returns the intersection of two sets as a new set.
intersection_update() – removes the items in the set that do not exist in another set.
isdisjoint() – returns True if two sets have a null intersection.
issubset() – returns True if another set contains this set.
issuperset() – returns True if this set contains another set.
pop() – removes and returns an element from the set.
remove() – removes an element from the set.
symmetric_difference() – returns the symmetric difference of two sets as a new set.
symmetric_difference_update() – inserts the symmetric difference from another set to this set.
union() – returns the union of sets in a new set.
update() – adds elements from another set to this set.
add()
The add() method in Python is used to add an element to a set. If the element is already present in the set, it won’t add a duplicate. The add() method returns None.
The syntax is:
set.add(element)
Example:
To buy Python books click the below links
Python Programming
Python Programming 2E
Handbook of Python Programming