Unit 3 Tuples
Unit 3 Tuples
Chapter 2: Tuples
Tuples
• Tuples are a sequence of values separated by commas.
• The values stored in the tuple can be of any type.
• They can be indexed by integers just like list.
• Tuples are immutable unlike lists.
• Defining tuples:
t=‘a’,’b’,’c’
or
t=(‘a’,’b’,’c’)
To create a tuple with a single
element, you have to include the final comma:
For each iteration through the loop, both key and value are
advanced to the next key-value pair in the dictionary.
Multiple Assignment with Dictionaries - Sorting the Dictionary by values
Output:
Convert tuple into a dictionary
Output:
• zip() function is used to combine two or more lists (or any other iterables) into
a single iterable, where elements from corresponding positions are paired
together.
• The resulting iterable contains tuples, where the first element from each list is
paired together, the second element from each list is paired together, and so
on.
• If the passed iterables have different lengths, the iterable with the least items
decides the length of the new iterator.
Remove empty tuple from a list of tuples
Output:
List Tuple Dictionaries
A list is a non-homogeneous A Tuple is also a non- A dictionary is also a non-
data structure that stores the homogeneous data structure that homogeneous data structure that
elements in sequence. stores elements in sequence. stores key-value pairs.
The list can be represented by [ Tuple can be represented by ( ) The dictionary can be represented
] by { }
The list allows duplicate Tuple allows duplicate elements The dictionary doesn’t allow
elements duplicate keys.
A list can be created using the Tuple can be created using the A dictionary can be created using
list() function tuple() function. the dict() function.
A list is mutable i.e we can A tuple is immutable i.e we can A dictionary is mutable, ut Keys are
make any changes in the list. not make any changes in the not duplicated.
tuple.
● For example:
Here, the first elements are both 0. Since they are equal, Python
moves to compare the second elements. The second element of
the first tuple, 3, is less than the second element of the second
tuple, 4. Therefore, (0, 3, 4) is considered smaller than (0, 4, 5).
Comparing Tuples
● Similarly, Here, the first elements are both 0, and the second
elements are 3 and 4, respectively. Since 3 is less
than 4, the first tuple is considered smaller.