0% found this document useful (0 votes)
39 views

Tuple in Puthon

Tuples can be used as keys in dictionaries because they are immutable. To use tuples as keys: 1. Create a dictionary and specify tuples as keys 2. Access values using the tuple keys 3. Tuples maintain their order and cannot be modified, making them suitable for use as immutable dictionary keys.

Uploaded by

greatrashidkhan1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Tuple in Puthon

Tuples can be used as keys in dictionaries because they are immutable. To use tuples as keys: 1. Create a dictionary and specify tuples as keys 2. Access values using the tuple keys 3. Tuples maintain their order and cannot be modified, making them suitable for use as immutable dictionary keys.

Uploaded by

greatrashidkhan1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit-5: Chapter-4 => Tuple

• Tuples are immutable


• Comparing tuples
• Tuple assignment
• Dictionaries and tuples
• Multiple assignment with dictionaries
• Using tuples as keys in dictionaries
• Sequences: strings, lists, and tuples.
What is tuple in Python?
• In Python, a tuple is a collection data type that is used to store an ordered, immutable
sequence of elements.
• Tuples are similar to lists in many ways, but they have a key difference: tuples are
immutable, meaning once a tuple is created, its elements cannot be changed or modified.
• This immutability makes tuples suitable for situations where the data should remain
constant throughout the program.
Here are some key characteristics of tuples in Python:
1. Ordered Sequence:
Tuples maintain the order in which elements are defined. The order of elements in a tuple is
preserved.
2. Immutable:
Once a tuple is created, you cannot add, remove, or modify elements in it. This makes tuples
different from lists, which are mutable.
3. Heterogeneous Elements:
Tuples can contain elements of different data types, including integers, floats, strings, and even
other tuples.
4. Enclosed in Parentheses:
Tuples are defined by enclosing the elements in parentheses (). For example: (1, 2, 'hello’).
5. Examples:
Example of creating a tuple: my_tuple = (1, 2, 'hello’)
6. Use Cases:
Tuples are often used to represent fixed collections of items, such as coordinates, RGB color
values, or records in a database where the data should not be modified.
Example
# Creating a tuple # Length of a tuple
my_tuple = (1, 2, 3, 'hello', (4, 5)) print(len(my_tuple))
print(type(my_tuple)) # Checking membership
# Accessing elements print(3 in my_tuple)
print(my_tuple[0]) # Iterating through elements
print(my_tuple[3]) for item in my_tuple:
print(my_tuple[4][1]) print(item)
# Slicing # Unpacking
print(my_tuple[1:4]) a, b, c, d, e = my_tuple
# Concatenation print("Unpacking",d)
new_tuple = my_tuple + (6, 7) #print(a, b, c, d, e)
print(new_tuple)
print(my_tuple)
Comparing Tuple
# Example 1
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
result = (tuple1 > tuple2) # False, because 3 < 4
print(result)

# Example 2
tuple3 = (1, 2, 'apple')
tuple4 = (1, 2, 'banana')
result = (tuple3 > tuple4) # False, because 'apple' < 'banana'
print(result)

# Example 3
tuple5 = (1, 2, 'apple')
tuple6 = (1, 2, 3)
result = (tuple5 > tuple6) #TypeError: '>' not supported between instances of 'str' and 'int'
print(result)
Comparing Tuple
• DSU stands for Decorate-Sort-Undecorate, and it 2. Sort:
is a programming pattern used to sort a
collection of elements based on some criteria. • Once the elements are decorated, the
• DSU stands for Decorate-Sort-Undecorate, and next step is to sort the collection based
it's a programming pattern often used in Python. on the associated keys.
This pattern involves three steps: decorating a • Python's built-in sorted() function can be
list, sorting it, and then undecorating it. It's a
flexible approach that allows you to customize used for this purpose.
the sorting process. • The sorted() function takes an iterable
• While the term is often associated with lists, the and returns a new sorted list.
same concept can be applied to tuples.
3. Undecorate:
• Here's a breakdown of the DSU pattern:
1. Decorate:
• After sorting, the final step is to
"undecorate" the sorted collection.
• The first step involves "decorating" the elements
of the collection. • This means removing the temporary
• This means associating each element with a key
association of elements with keys.
based on which the sorting will be performed. • The result is a sorted collection of the
• In Python, this is often done using a function that original elements.
takes an element as input and returns a key. The
key can be a single value or a tuple of values.
# Example: Sorting a list of tuples based on the second element of each tuple
# Step 1: Decorate In this example:
def decorate(tuple): • The decorate function takes a tuple and returns
# Decorating with the second element as the key its second element as the key.
return tuple[1] • The sorted() function is used with the key
parameter set to the decorate function,
indicating that the sorting should be based on
# Original list of tuples the second element of each tuple.
my_list = [(1, 5), (2, 3), (3, 7), (4, 1)] • The result is a new list of tuples sorted based on
the second element of each tuple.

# Step 2: Sort
sorted_list = sorted(my_list, key=decorate)

# Step 3: Undecorate
result = sorted_list

# Displaying the result


print(result)
# Example: Sorting a list of tuples based on the second element of each tuple
# Step 1: Decorate 1. Decorate Function (decorate):
def decorate(tuple): The decorate function takes a tuple as an argument.
# Decorating with the second element as the key It returns the second element of the tuple (tuple[1]),
effectively using the second element as the key for sorting.
return tuple[1]
2. Original List (my_list):
my_list is a list of tuples, where each tuple has two elements.
# Original list of tuples 3. Sort (sorted_list):
my_list = [(1, 5), (2, 3), (3, 7), (4, 1)] The sorted function is used to sort the original list (my_list).
The key parameter is set to the decorate function, meaning
# Step 2: Sort the sorting will be based on the second element of each tuple.

sorted_list = sorted(my_list, key=decorate) The result is stored in the variable sorted_list.


4.Undecorate (result):
In this case, the undecorate step is not explicitly performed.
# Step 3: Undecorate The variable result is assigned the value of sorted_list.
result = sorted_list 5.Displaying the Result (print(result)):
The sorted list (sorted_list) is printed, showing the tuples
# Displaying the result sorted based on their second elements.

print(result)
Tuple Assignment
Tuple assignment in Python is a feature that allows Explanation:
you to assign multiple variables simultaneously
using a single tuple. It's a convenient way to In this example, coordinates is a tuple with
unpack values from a tuple and assign them to two elements (3 and 7).
multiple variables in a single line. Tuple assignment
is commonly used when working with functions
The line x, y = coordinates is a tuple
that return multiple values, or when dealing with assignment, where the values from the
data in tuples. tuple coordinates are unpacked and
Example: assigned to the variables x and y.
# Creating a tuple After the assignment, x will be 3, and y will
coordinates = (3, 7) be 7.
# Tuple assignment
x, y = coordinates
# Printing the values of x and y
print("x =", x)
print("y =", y)
You can also use tuple assignment with functions that return multiple values.
# Function returning multiple values Explanation:
def get_coordinates(): In this example, the function
return 5, 10 get_coordinates returns a tuple (5, 10),
and tuple assignment is used to assign
# Tuple assignment with function return values these values to variables a and b.
a, b = get_coordinates()

# Printing the values of a and b


print("a =", a)
print("b =", b)
Dictionaries and tuples
• Dictionaries have a method called items that returns a list of tuples, where each tuple is a
key-value pair:
d = {'c':10, 'a':1, 'b':22}
t =list(d.items())
print(t)

t.sort()
print(t)
Multiple assignment with dictionaries
• Combining items, tuple assignment, and for, you can see a nice code pattern for
traversing the keys and values of a dictionary in a single loop:
d = {'a':10, 'b':1, 'c':22}
for key, val in list(d.items()):
print(val, key)
• This loop has two iteration variables because items returns a list of tuples and key, val is
a tuple assignment that successively iterates through each of the key-value pairs in the
dictionary (hash key order -> no particular order).
• For each iteration through the loop, both key and value are advanced to the next key-
value pair in the dictionary.
• To do this, we first make a list of tuples where each tuple is (value, key). The items
method would give us a list of (key, value) tuples, but this time we want to sort by
value, not key. Once we have constructed the list with the value-key tuples, it is a simple
matter to sort the list in reverse order and print out the new, sorted list.

d = {'a':10, 'b':1, 'c':22}


l = list()
for key, val in d.items():
l.append((val, key))
print('Before Sorting:',l)
l.sort(reverse=False)
print('After Sorting:',l)
l.sort(reverse=True)
print('After Sorting:',l)
Using tuples as keys in dictionaries
• In Python, dictionaries are a collection of key-value pairs, where each key must be
unique.
• Keys in dictionaries must be immutable, meaning they cannot be changed after they are
created.
• Tuples, being immutable, can be used as keys in dictionaries.
• This can be useful in scenarios where you need to create a mapping between a set of
values and another value.
# Creating a dictionary with tuples as keys • In this example, we have a dictionary called
employee_salaries = { employee_salaries where the keys are tuples
('John', 'Doe'): 50000, representing the names of employees, and
the values are their corresponding salaries.
('Jane', 'Smith'): 60000,
The tuples are used as keys because they are
('Bob', 'Johnson'): 55000 immutable and can uniquely represent each
} employee.
# Accessing values using tuples as keys • Keep in mind that not all data types are
print(employee_salaries[('John', 'Doe')]) # Output: suitable for use as dictionary keys.
50000 Immutable types like tuples, strings, and
print(employee_salaries[('Bob', 'Johnson')]) # Output: numbers are valid, while mutable types like
55000 lists and dictionaries are not. Using tuples as
# Adding a new entry with a tuple key keys can be a convenient way to represent
employee_salaries[('Alice', 'Williams')] = 62000 composite keys when a single value is not
sufficient for unique identification.
# Displaying the updated dictionary
print(employee_salaries)
Sequences: strings, lists, and tuples

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy