Unit II
Unit II
2.1 List
What is a List?
• A List is a collection of ordered, mutable
(changeable) elements.
• Lists can store items of different data types —
integers, strings, even other lists.
• Lists are defined using square brackets [ ].
Creating a List
my_list = [10, 20, 30, "Python", 4.5]
print(my_list)
Output:
[10, 20, 30, 'Python', 4.5]
Deleting Elements
You can delete an element using del, pop(), or
remove().
del my_list[0] # Deletes by index
my_list.pop() # Removes last item
my_list.remove(30) # Removes value 30
Creating a Tuple
my_tuple = (10, 20, 30, "Python", 5.5)
print(my_tuple)
Output:
(10, 20, 30, 'Python', 5.5)
# Unpacking
name, age, city = person
print(name) # Aarti
print(city) # Pune
2.3 Set
What is a Set?
• A Set is an unordered collection of unique and
immutable elements.
• Defined using curly braces {} or the set()
constructor.
• Duplicates are automatically removed.
• Sets are mutable, but the elements must be
immutable (e.g., numbers, strings, tuples).
Creating a Set
my_set = {1, 2, 3, 4, 4, 5}
print(my_set)
Output:
{1, 2, 3, 4, 5} → (Duplicate 4 is removed)
empty_set = set() # Correct way to create an empty set
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
What is a Dictionary?
• A Dictionary is an unordered collection of data in
key-value pairs.
• Each key is unique, and keys are used to access
values.
• Defined using curly braces {} or the dict()
constructor.
Creating a Dictionary
student = {
"name": "Ashwini",
"age": 20,
"city": "Pune"
}
empty_dict = dict()
Accessing Values
print(student["name"]) # Ashwini
print(student.get("age")) # 20
Updating and Deleting Elements
student["age"] = 21 # Update
student["email"] = "[email protected]" # Add new key-
value
del student["city"] # Delete key
student.pop("email") # Remove key using pop()