0% found this document useful (0 votes)
4 views15 pages

Tuple and Dictionary Practical and SETS in Python

The document provides an overview of tuples and dictionaries in Python, highlighting their key features, such as tuples being ordered and immutable, while dictionaries are unordered and mutable. It includes examples of creating, accessing, and manipulating both data structures, along with a comparison of their functionalities. Additionally, it introduces sets in Python, explaining their unique properties and fundamental operations like union, intersection, and difference.

Uploaded by

princesarwa07
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)
4 views15 pages

Tuple and Dictionary Practical and SETS in Python

The document provides an overview of tuples and dictionaries in Python, highlighting their key features, such as tuples being ordered and immutable, while dictionaries are unordered and mutable. It includes examples of creating, accessing, and manipulating both data structures, along with a comparison of their functionalities. Additionally, it introduces sets in Python, explaining their unique properties and fundamental operations like union, intersection, and difference.

Uploaded by

princesarwa07
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

Python Basics: Tuples and Dictionaries with Examples

1. Tuples in Python

A tuple is an ordered, immutable (unchangeable) collection of elements enclosed


in parentheses ().

Key Features of Tuples:

✔ Ordered (elements have a fixed position)


✔ Immutable (cannot modify after creation)
✔ Allows duplicate values
✔ Can store different data types

10 Tuple Examples

1. Creating a Tuple
fruits = ("apple", "banana", "cherry")
print(fruits) # Output: ('apple', 'banana', 'cherry')

2. Accessing Tuple Items (Indexing)


print(fruits[1]) # Output: banana

3. Negative Indexing (Access from End)


print(fruits[-1]) # Output: cherry

4. Slicing a Tuple
print(fruits[1:3]) # Output: ('banana', 'cherry')

5. Tuple with Mixed Data Types


mixed_tuple = (1, "hello", 3.14, True)
print(mixed_tuple) # Output: (1, 'hello', 3.14, True)

6. Tuple with Single Element (Note the Comma)


single_element = ("python",) # Comma is necessary
print(single_element) # Output: ('python',)

7. Unpacking a Tuple
a, b, c = fruits
print(a, b, c) # Output: apple banana cherry

8. Concatenating Tuples
tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 'a', 'b', 'c')

9. Finding Length of a Tuple


print(len(fruits)) # Output: 3

10. Checking if an Item Exists


print("apple" in fruits) # Output: True

2. Dictionaries in Python

A dictionary is an unordered, mutable collection of key-value pairs enclosed in


curly braces {}.

Key Features of Dictionaries:

✔ Unordered (no fixed index)


✔ Mutable (can modify after creation)
✔ Keys must be unique and immutable (e.g., strings, numbers, tuples)
✔ Values can be any data type

10 Dictionary Examples

1. Creating a Dictionary
student = {"name": "Alice", "age": 20, "grade": "A"}
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}

2. Accessing Dictionary Values


print(student["name"]) # Output: Alice

3. Adding a New Key-Value Pair


student["city"] = "New York"
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A', 'city': 'New York'}

4. Modifying a Value
student["age"] = 21
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'New York'}

5. Removing a Key-Value Pair


del student["grade"]
print(student) # Output: {'name': 'Alice', 'age': 21, 'city': 'New York'}

6. Checking if a Key Exists


print("age" in student) # Output: True

7. Getting All Keys


print([Link]()) # Output: dict_keys(['name', 'age', 'city'])

8. Getting All Values


print([Link]()) # Output: dict_values(['Alice', 21, 'New York'])

9. Looping Through a Dictionary


for key, value in [Link]():
print(f"{key}: {value}")

Output:
name: Alice
age: 21
city: New York

10. Dictionary with Mixed Keys


mixed_dict = {1: "one", "two": 2, (3, 4): "tuple key"}
print(mixed_dict) # Output: {1: 'one', 'two': 2, (3, 4): 'tuple key'}
Summary Table: Tuples vs. Dictionaries

Final Notes

 Tuples are faster than lists for fixed data.


 Dictionaries are optimized for fast lookups using keys.
 Both are widely used in Python for different scenarios.

Would you like more advanced operations (e.g., nested dictionaries, tuple
methods)? 🚀

Python Operations on Tuples and Dictionaries (20+ Examples)

1. Tuple Operations

Tuples are immutable, but you can perform various operations on them.

Example 1: Creating a Tuple


colors = ("red", "green", "blue")
print(colors) # Output: ('red', 'green', 'blue')

Example 2: Accessing Elements (Indexing)


print(colors[1]) # Output: green

Example 3: Negative Indexing


print(colors[-1]) # Output: blue

Example 4: Slicing a Tuple


print(colors[0:2]) # Output: ('red', 'green')

Example 5: Concatenating Tuples


more_colors = ("yellow", "purple")
all_colors = colors + more_colors
print(all_colors) # Output: ('red', 'green', 'blue', 'yellow', 'purple')

Example 6: Repeating a Tuple


repeated = ("hi",) * 3
print(repeated) # Output: ('hi', 'hi', 'hi')

Example 7: Checking Membership


print("red" in colors) # Output: True
Example 8: Finding Length
print(len(colors)) # Output: 3

Example 9: Unpacking a Tuple


a, b, c = colors
print(a, b, c) # Output: red green blue

Example 10: Converting List to Tuple


my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)

Example 11: Counting Occurrences


numbers = (1, 2, 3, 2, 4, 2)
print([Link](2)) # Output: 3

Example 12: Finding Index of an Element


print([Link](3)) # Output: 2

2. Dictionary Operations

Dictionaries are mutable and support key-value pair operations.

Example 1: Creating a Dictionary


student = {"name": "Alice", "age": 20, "grade": "A"}
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}

Example 2: Accessing Values


print(student["name"]) # Output: Alice

Example 3: Adding a New Key-Value Pair


student["city"] = "New York"
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A', 'city': 'New York'}

Example 4: Modifying a Value


student["age"] = 21
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'New York'}

Example 5: Removing a Key-Value Pair


del student["grade"]
print(student) # Output: {'name': 'Alice', 'age': 21, 'city': 'New York'}

Example 6: Checking if a Key Exists


print("age" in student) # Output: True

Example 7: Getting All Keys


print([Link]()) # Output: dict_keys(['name', 'age', 'city'])

Example 8: Getting All Values


print([Link]()) # Output: dict_values(['Alice', 21, 'New York'])

Example 9: Getting Key-Value Pairs


print([Link]()) # Output: dict_items([('name', 'Alice'), ('age', 21), ('city',
'New York')])

Example 10: Looping Through a Dictionary


for key, value in [Link]():
print(f"{key}: {value}")

Output:
name: Alice
age: 21
city: New York

Example 11: Updating a Dictionary


[Link]({"age": 22, "country": "USA"})
print(student) # Output: {'name': 'Alice', 'age': 22, 'city': 'New York', 'country':
'USA'}

Example 12: Clearing a Dictionary


[Link]()
print(student) # Output: {}

Example 13: Copying a Dictionary


student = {"name": "Bob", "age": 25}
student_copy = [Link]()
print(student_copy) # Output: {'name': 'Bob', 'age': 25}

Example 14: Removing & Returning a Value


age = [Link]("age")
print(age) # Output: 25
print(student) # Output: {'name': 'Bob'}

Example 15: Default Value for Missing Key


print([Link]("grade", "N/A")) # Output: N/A

Example 16: Nested Dictionary


school = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
print(school["student1"]["name"]) # Output: Alice

Example 17: Dictionary Comprehension


squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
SETS in Python Programming

python set operations, and you've asked for "above with explanation." It seems
you're looking for a more detailed explanation of each set operation, perhaps with a
focus on why they are useful and how they work conceptually.

Let's break down each set operation with explanations and simple, suitable
examples, expanding on the concepts from your initial response.

Python Set Operations: A Comprehensive Explanation

Sets in Python are unordered collections of unique elements. This means:

1. Unordered: The elements in a set do not have a specific sequence or index.


When you print a set, the order might appear different from how you
inserted the elements.
2. Unique: A set cannot contain duplicate elements. If you try to add an
element that's already in the set, it simply won't be added again. This
property makes sets extremely useful for de-duplication tasks.

Because of these characteristics, sets are ideal for performing mathematical set
operations like union, intersection, difference, and symmetric difference, which are
fundamental in various computational tasks.

Creating Sets

Before diving into operations, let's recap how to create sets.

 Using set() constructor: You can convert any iterable (like a list, tuple, or
string) into a set. This is particularly useful for removing duplicate elements
from an existing collection.

# Example 1: Creating a set from a list


my_list = [1, 2, 3, 2, 4, 1, 5]
set_from_list = set(my_list)
print(f"Set from list: {set_from_list}")
# Explanation: The set() constructor takes the list and automatically filters
out duplicates.
# Output: Set from list: {1, 2, 3, 4, 5} (order may vary)

# Example 2: Creating a set from a string (characters become elements)


my_string = "hello"
set_from_string = set(my_string)
print(f"Set from string: {set_from_string}")
# Explanation: Each unique character in "hello" becomes an element.
# Output: Set from string: {'e', 'o', 'l', 'h'} (order may vary)
 Using curly braces {}: This is a more concise way to directly define a set,
similar to how dictionaries are defined, but without key-value pairs.

# Example: Direct set creation


fruits = {"apple", "banana", "cherry"}
print(f"Fruits set: {fruits}")
# Explanation: You directly list the unique elements within curly braces.
# Output: Fruits set: {'banana', 'apple', 'cherry'} (order may vary)

# Important Note: To create an empty set, you must use set()


empty_set = set()
print(f"Empty set created using set(): {empty_set}") # Output: Empty set
created using set(): set()

# {} creates an empty dictionary, not an empty set


# empty_dict = {}
# print(type(empty_dict)) # Output: <class 'dict'>

Fundamental Set Operations

Let's consider two sets, A and B, for our explanations.

set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}
print(f"Set A: {set_A}")
print(f"Set B: {set_B}")

1. Union (AcupB)

 Concept: The union of two sets creates a new set containing all unique
elements from both original sets. If an element is present in both sets, it
appears only once in the union, respecting the unique property of sets.
 Analogy: Imagine you have two baskets of different types of toys. The
union is putting all the unique toys from both baskets into a new, single
basket.
 When to use:
o Combining data from multiple sources while ensuring no duplicates.
o Getting a complete list of all distinct items across different categories.
 Methods:
o set_A.union(set_B): This method explicitly calls the union operation.
o set_A | set_B: This is the more concise and commonly used operator
for union.

# Using the method


union_result_method = set_A.union(set_B)
print(f"Union (method): {union_result_method}")
# Explanation: Combines all unique elements from set_A and set_B. {1,2,3}
from A, {6,7,8} from B, and {4,5} which are common.
# Output: Union (method): {1, 2, 3, 4, 5, 6, 7, 8}

# Using the operator


union_result_operator = set_A | set_B
print(f"Union (operator): {union_result_operator}")
# Output: Union (operator): {1, 2, 3, 4, 5, 6, 7, 8}

2. Intersection (AcapB)

 Concept: The intersection of two sets creates a new set containing only the
elements that are common to both original sets.
 Analogy: If you have two lists of books, the intersection would be the books
that appear on both lists.
 When to use:
o Finding common items between two groups or datasets.
o Identifying overlapping categories or shared characteristics.
 Methods:
o set_A.intersection(set_B): The explicit method call.
o set_A & set_B: The concise operator for intersection.

# Using the method


intersection_result_method = set_A.intersection(set_B)
print(f"Intersection (method): {intersection_result_method}")
# Explanation: Finds elements present in both set_A and set_B.
# Output: Intersection (method): {4, 5}

# Using the operator


intersection_result_operator = set_A & set_B
print(f"Intersection (operator): {intersection_result_operator}")
# Output: Intersection (operator): {4, 5}

3. Difference (A−B)

 Concept: The difference of set A from set B (written as A−B) creates a new
set containing elements that are present in set A but NOT in set B. Note
that A−B is generally different from B−A.
 Analogy: You have a list of all your friends (A) and a list of friends who
attended a party (B). A−B would give you the friends who didn't attend the
party.
 When to use:
o Filtering out elements from one collection that exist in another.
o Finding unique items in one list compared to a reference list.
 Methods:
o set_A.difference(set_B): The explicit method call.
o set_A - set_B: The concise operator for difference.

# Using the method (A - B)


difference_A_minus_B = set_A.difference(set_B)
print(f"Difference (A - B): {difference_A_minus_B}")
# Explanation: Elements {1, 2, 3} are in set_A but not in set_B.
# Output: Difference (A - B): {1, 2, 3}

# Using the method (B - A) - demonstrates non-commutativity


difference_B_minus_A = set_B.difference(set_A)
print(f"Difference (B - A): {difference_B_minus_A}")
# Explanation: Elements {6, 7, 8} are in set_B but not in set_A.
# Output: Difference (B - A): {8, 6, 7} (order may vary)

# Using the operator


difference_A_minus_B_operator = set_A - set_B
print(f"Difference (A - B) using operator:
{difference_A_minus_B_operator}")
# Output: Difference (A - B) using operator: {1, 2, 3}

4. Symmetric Difference (ADeltaB)

 Concept: The symmetric difference of two sets creates a new set containing
elements that are in either set, but not in their intersection. In simpler
terms, it's the elements that are unique to each set (not common to both). It
can also be thought of as (AcupB)−(AcapB).
 Analogy: You have two lists of ingredients for two different recipes. The
symmetric difference would be the ingredients that are only in the first
recipe or only in the second recipe, but not in both.
 When to use:
o Finding items that have changed between two versions of a dataset.
o Identifying elements that are unique to one of two overlapping groups.
 Methods:
o set_A.symmetric_difference(set_B): The explicit method call.
o set_A ^ set_B: The concise operator for symmetric difference.

# Using the method


symmetric_diff_result_method = set_A.symmetric_difference(set_B)
print(f"Symmetric Difference (method): {symmetric_diff_result_method}")
# Explanation: Elements {1,2,3} are only in A, and {6,7,8} are only in B.
# Output: Symmetric Difference (method): {1, 2, 3, 6, 7, 8}

# Using the operator


symmetric_diff_result_operator = set_A ^ set_B
print(f"Symmetric Difference (operator):
{symmetric_diff_result_operator}")
# Output: Symmetric Difference (operator): {1, 2, 3, 6, 7, 8}

Other Useful Set Methods

These methods allow you to check relationships between sets without necessarily
creating a new set.

Let's use:

set_small = {1, 2}
set_medium = {1, 2, 3, 4}
set_large = {1, 2, 3, 4, 5, 6}
set_other = {5, 6, 7}

5. issubset()

 Concept: set_A.issubset(set_B) returns True if all elements of set_A are


also present in set_B. It essentially checks if set_A is "contained within"
set_B.
 Analogy: Is the set of "primary colors" a subset of "all colors"? Yes,
because all primary colors are also colors.
 Operator equivalent: set_A <= set_B (less than or equal to, implying
subset or equal). set_A < set_B (strict subset, meaning set_A is a subset of
set_B but not equal to set_B).

Python

print(f"Is set_small a subset of set_medium?


{set_small.issubset(set_medium)}")
# Explanation: Both 1 and 2 (elements of set_small) are in set_medium.
# Output: Is set_small a subset of set_medium? True

print(f"Is set_medium a subset of set_small?


{set_medium.issubset(set_small)}")
# Explanation: 3 and 4 are in set_medium but not in set_small.
# Output: Is set_medium a subset of set_small? False

print(f"Is set_small <= set_medium? {set_small <= set_medium}") #


Operator equivalent
# Output: Is set_small <= set_medium? True

6. issuperset()

 Concept: set_A.issuperset(set_B) returns True if all elements of set_B are


also present in set_A. It checks if set_A "contains" set_B.
 Analogy: Is the set of "all colors" a superset of "primary colors"? Yes,
because all primary colors are included in "all colors".
 Operator equivalent: set_A >= set_B (greater than or equal to, implying
superset or equal). set_A > set_B (strict superset, meaning set_A is a
superset of set_B but not equal to set_B).

print(f"Is set_medium a superset of set_small?


{set_medium.issuperset(set_small)}")
# Explanation: Both 1 and 2 (elements of set_small) are in set_medium.
# Output: Is set_medium a superset of set_small? True

print(f"Is set_small a superset of set_medium?


{set_small.issuperset(set_medium)}")
# Explanation: set_small does not contain all elements of set_medium.
# Output: Is set_small a superset of set_medium? False

print(f"Is set_medium >= set_small? {set_medium >= set_small}") #


Operator equivalent
# Output: Is set_medium >= set_small? True

7. isdisjoint()

 Concept: set_A.isdisjoint(set_B) returns True if the two sets have no


elements in common (their intersection is an empty set).
 Analogy: Are the set of "even numbers" and the set of "odd numbers"
disjoint? Yes, they have no numbers in common.
 When to use:
o Checking for exclusivity between two groups.
o Ensuring that two sets of categories do not overlap.

print(f"Are set_small and set_other disjoint?


{set_small.isdisjoint(set_other)}")
# Explanation: set_small contains {1, 2} and set_other contains {5, 6, 7}. No
common elements.
# Output: Are set_small and set_other disjoint? True

print(f"Are set_medium and set_other disjoint?


{set_medium.isdisjoint(set_other)}")
# Explanation: set_medium contains {1, 2, 3, 4} and set_other contains {5,
6, 7}. No common elements.
# Output: Are set_medium and set_other disjoint? True

# Let's create an example that's NOT disjoint


set_overlapping = {3, 4, 9}
print(f"Are set_medium and set_overlapping disjoint?
{set_medium.isdisjoint(set_overlapping)}")
# Explanation: Both sets contain 3 and 4, so they are not disjoint.
# Output: Are set_medium and set_overlapping disjoint? False

Practical Applications of Set Operations

Sets are not just for theoretical math; they are incredibly practical in programming.

1. Data Cleaning and Deduplication: The most straightforward use. If you have a
list with many duplicate entries, converting it to a set and back to a list (if order
matters) is the most efficient way to get unique elements.

customer_ids = [101, 105, 103, 101, 102, 105, 104]


unique_customer_ids = list(set(customer_ids))
print(f"Original IDs: {customer_ids}")
print(f"Unique IDs: {unique_customer_ids}")
# Output: Unique IDs: [1, 2, 3, 4, 5] (order might vary)

2. Membership Testing (Fast Lookups): Checking if an element is in a set is


extremely fast (average O(1) time complexity) because sets are implemented using
hash tables. This is much faster than checking membership in a list for large
collections (which is O(n)).

allowed_users = {"Alice", "Bob", "Charlie", "David"}


user_to_check = "Alice"

if user_to_check in allowed_users:
print(f"{user_to_check} is an allowed user.")
else:
print(f"{user_to_check} is NOT an allowed user.")

# Output: Alice is an allowed user.

3. Comparing Lists/Groups: Identifying commonalities, differences, or unique


elements between two or more collections.

# Scenario: Students enrolled in two different courses


math_students = {"Alice", "Bob", "Charlie", "David"}
physics_students = {"Bob", "David", "Eve", "Frank"}

# Who is taking both Math and Physics? (Intersection)


both_courses = math_students.intersection(physics_students)
print(f"Students taking both courses: {both_courses}")
# Output: Students taking both courses: {'David', 'Bob'}

# Who is taking Math but NOT Physics? (Difference)


only_math = math_students.difference(physics_students)
print(f"Students only taking Math: {only_math}")
# Output: Students only taking Math: {'Charlie', 'Alice'}

# All unique students enrolled in either course (Union)


all_students = math_students.union(physics_students)
print(f"All unique students: {all_students}")
# Output: All unique students: {'Eve', 'Frank', 'Alice', 'Charlie', 'David', 'Bob'}

4. Finding Missing Elements: If you have a complete set of expected items and
another set of received items, you can easily find what's missing.

all_products = {"Laptop", "Mouse", "Keyboard", "Monitor", "Webcam"}


shipped_products = {"Laptop", "Mouse", "Keyboard"}

missing_products = all_products - shipped_products


print(f"Products still to be shipped: {missing_products}")
# Output: Products still to be shipped: {'Monitor', 'Webcam'}

By understanding these operations and their underlying concepts, you can leverage
Python sets to write more efficient, readable, and powerful code for a wide array of
data manipulation and analytical tasks.

You might also like