0% found this document useful (0 votes)
15 views7 pages

Tuple, Dictionarie, and Set

The document provides an overview of three data structures in Python: tuples, dictionaries, and sets. Tuples are ordered and immutable collections, dictionaries are unordered collections of key-value pairs, and sets are unordered collections of unique elements. Each structure has specific use cases, such as using tuples for immutable data, dictionaries for fast lookups, and sets for unique items and mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views7 pages

Tuple, Dictionarie, and Set

The document provides an overview of three data structures in Python: tuples, dictionaries, and sets. Tuples are ordered and immutable collections, dictionaries are unordered collections of key-value pairs, and sets are unordered collections of unique elements. Each structure has specific use cases, such as using tuples for immutable data, dictionaries for fast lookups, and sets for unique items and mathematical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

tuple, dictionarie, and set

Data Structures in Python

A data structure is a way of organizing and storing data efficiently. Apart from standard
types like strings and integers, Python provides tuples, dictionaries, and sets for
handling collections of data in different ways.

1. Tuples

Definition
• A tuple is an ordered, immutable collection of elements.
• Elements in a tuple cannot be modified after creation.
• Tuples can store multiple data types.
• Tuples use parentheses () or can be defined without them (Tuple
Packing).

Creating a Tuple

a = (1, 2)
b = "eat", "dinner", "man", "boy" # Tuple Packing
print(a) # Output: (1, 2)
print(type(a)) # Output: <class 'tuple'>

Empty Tuple

empty_tuple = ()
print(type(empty_tuple)) # Output: <class 'tuple'>

Single Element Tuple


• A trailing comma is required to distinguish it from a normal variable.

a = ("Hamburger",) # Correct
print(type(a)) # Output: <class 'tuple'>
b = ("Hamburger") # Incorrect
print(type(b)) # Output: <class 'str'>

Tuple vs List

Accessing Elements
• Indexing (0-based)
• Negative Indexing (Last element is -1)

myTuple = (1, 15, 13, 18, 19)


print(myTuple[2]) # Output: 13
print(myTuple[-1]) # Output: 19

Slicing

print(myTuple[1:4]) # Output: (15, 13, 18)


print(myTuple[:3]) # Output: (1, 15, 13)

Operations on Tuples
• Concatenation
a = (1, 2, 3)
b = (4, 5, 6)
print(a + b) # Output: (1, 2, 3, 4, 5, 6)

Repetition

print(a * 3) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

Finding Min/Max

print(min(a)) # Output: 1
print(max(a)) # Output: 3

Converting List to Tuple

myList = [1, 2, 3, 4]
myTuple = tuple(myList)
print(myTuple) # Output: (1, 2, 3, 4)

Tuple in Functions

Variable Length Arguments

def printNums(a, b, *more):


print(a)
print(b)
print(more)

printNums(1, 2, 3, 4, 5)
# Output: 1, 2, (3, 4, 5)

Returning Multiple Values

def sum_diff(a, b):


return a + b, a - b # Returns a tuple
print(sum_diff(5, 3)) # Output: (8, 2)

2. Dictionaries

Definition
• A dictionary is an unordered collection of key-value pairs.
• Keys are unique and immutable (e.g., strings, numbers, tuples).
• Values can be mutable or immutable.
• Uses curly brackets {}.

Creating a Dictionary

myDict = {"red": "boy", 6: 4, "name": "John"}


months = {1: "January", 2: "February"}

Accessing Elements

print(myDict["red"]) # Output: boy


print(months.get(3, "Not Found")) # Output: Not Found

Adding/Updating Elements

myDict["age"] = 25 # Adding a new key-value pair


myDict["name"] = "Doe" # Updating an existing value

Removing Elements

myDict.pop("age") # Removes key "age"


myDict.clear() # Removes all elements
del myDict # Deletes dictionary

Dictionary Methods
• Get All Keys
• Get All Keys

print(myDict.keys()) # Output: dict_keys(['red', 6, 'name'])

Get All Values

print(myDict.values()) # Output: dict_values(['boy', 4, 'John'])

Get All Items

print(myDict.items()) # Output: dict_items([('red', 'boy'), (6, 4), ('name', 'John')])

Merging Dictionaries

dict1 = {1: "A", 2: "B"}


dict2 = {3: "C", 4: "D"}
dict1.update(dict2)
print(dict1) # Output: {1: 'A', 2: 'B', 3: 'C', 4: 'D'}

Iterating Over a Dictionary

for key, value in myDict.items():


print(key, ":", value)

3. Sets

Definition
• A set is an unordered collection of unique elements.
• No duplicate values are allowed.
• Mutable (you can add/remove elements), but elements inside must be
immutable.
• Uses curly brackets {} or set() function.

Creating a Set

mySet = {"apple", "banana", "cherry"}


mySet = {"apple", "banana", "cherry"}
anotherSet = set([1, 2, 3, 4, 5])

Adding & Removing Elements

mySet.add("orange") # Adds an element


mySet.remove("banana") # Removes an element (throws error if not found)
mySet.discard("grape") # Removes without error if not found
mySet.clear() # Removes all elements

Set Operations

Union (|)

A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # Output: {1, 2, 3, 4, 5}

Intersection (&)

print(A & B) # Output: {3}

Difference (-)

print(A - B) # Output: {1, 2}

Subset & Superset

print(A <= B) # False (A is not a subset of B)


print(A >= B) # False (A is not a superset of B)

Tuples: Ordered, Immutable, Indexing Supported.


Dictionaries: Unordered, Mutable, Key-Value Mapping.
Sets: Unordered, Unique Elements, No Indexing.

Each structure has unique advantages:


• Use tuples when data should not change.
• Use dictionaries when you need fast key-value lookup.
• Use sets for unique items and mathematical operations.

You might also like