Learn Advanced Data Types in Python
Compare Python List, Tuple, Set, and Dict features, syntax, and use cases with simple examples to choose the right data type for speed, order, and mutability.
Python Data Structures: List, Tuple, Set, and Dictionary
When working with Python, one of the most important things to understand is how to store and manage collections of data. Python provides several built-in data structures to handle this: List, Tuple, Set, and Dictionary. Each has its own unique properties and use cases.
1. List – Ordered and Mutable
A list is an ordered collection of items that is mutable, meaning you can change it after it’s created. It can store items of different data types.
Key Features:
-
Ordered (items have a defined order)
-
Mutable (can be changed)
-
Allows duplicate items
-
Allows mixed data types
Example:
Places=[“Hyderabad”,”Punjab”,”Gujarat”,”Chennai”]
Print(places) #Output: [“Hyderabad”,”Punjab”,”Gujarat”,”Chennai”]
List Indexing
Accessing Elements
You use indexes to access individual items in a list.
Example:
my_list = ['a', 'b', 'c', 'd']
print(my_list[0]) # Output: a
print(my_list[2]) # Output: c
Negative Indexing
Access items from the end using negative indexes.
Example:
print(my_list[-1]) # Output: d
print(my_list[-2]) # Output: c
Modifying Lists
Adding Elements
append(): Add at end
Example:
lst=[1,2]
lst.append(99)
print(lst) #Output: [1,2,99]
insert(index, value): Add at specific position
Example:
lst.insert(1, "inserted")
print(lst) #Output: [1,”inserted”,99]
Removing Elements
remove(value): Removes first occurrence
Example:
p=[1,2,10,4,10]
p.remove(10)
print(p) #Output: [1,2,4,10]
pop([index]): Removes and returns item
p.pop() # Removes last
p.pop(1) # Removes second item
List Length
len() is used to find length of list and other iterable data types
Example:
P=[1,2,3,4,5 ]
print(len(p)) #Output: 5
2. Tuple – Ordered and Immutable
A tuple is similar to a list but immutable — once created, you cannot change, add, or remove elements from it.
Key Features
-
Tuples preserve the order of elements, just like lists.
-
They are immutable, meaning their contents stay fixed once created.
-
Tuples also support duplicate values, allowing the same item to occur multiple times.
-
They can store multiple data types, making them suitable for fixed collections of items.
Example:
Places=(“Hyderabad”,”Punjab”,”Gujarat”,”Chennai”)
Print(places) #Output: (“Hyderabad”,”Punjab”,”Gujarat”,”Chennai”)
Example:
empty=() #empty tuple
Indexing
Like lists tuples can also access each item using indexing
Example:
A=(1,2,3,”ravi”,”hello”)
print(A[0]) #Output: 1
print(A[-2]) #Output: ravi
Tuple is Immutable
You cannot change a tuple after it's created:
Example:
t = (1, 2, 3)
t[0] = 10 # This will raise a TypeError
Tuple Operations
Concatenation
Example:
a = (1, 2)
b = (3, 4)
print(a + b) # Output: (1, 2, 3, 4)
Repetition
a = (1, 2)
print(a * 3) # Output: (1, 2, 1, 2, 1, 2)
Tuple Functions
len():
Returns number of elements in tuple.
Example:
t = (1, 2, 3)
print(len(t)) # Output: 3
count()
Returns number of times a value appears.
t = (1, 2, 1, 3)
print(t.count(1)) # Output: 2
Nested tuple:
Tuples can contain other tuples:
nested = ((1, 2), (3, 4), (5, 6))
print(nested[1][2]) #Output:4
range – Immutable sequence of numbers
Example:
for i in range(3):
print(i) #Output: 0, 1, 2
Looping Through Tuples
Using for loop:
Example:
t = (10, 20) #Output:
for item in t: 10
print(item) 20
3.Dictionary – Key-Value Pairs
A dictionary stores data in key-value pairs. It’s Python’s version of a hash map or associative array.
Key Features
-
A dictionary stores data in key-value pairs, allowing you to access values by their corresponding keys.
-
Keys in a dictionary must be unique and immutable, while values can be of any data type.
-
Dictionaries are mutable, so you can add, update, or remove key-value pairs.
-
They maintain the insertion order of items (as of Python 3.7 and later), making iteration predictable.
Example:
person = {
"name": "Anita",
"skills": ["Python", "Django"],
"details": {"age": 28, "city": "Delhi"}
}
print(student[“skills]) #Output: ["Python", "Django"]
Example:
Empty_dictionary = {} # This creates an empty dictionary
Accessing Dictionary Elements
You access values using their keys.
Example:
print(person["name"]) # Output: Anita
print(person["skills"]) # Output: ['Python', 'Django']
If the key doesn't exist, Python will raise a KeyError.
Use .get() to avoid errors:
Example:
person = {
"name": "Anita",
"skills": ["Python", "Django"],
"details": {"age": 28, "city": "Delhi"}
}
print(person.get("email")) # Output: None
Modifying Dictionaries
Changing Values:
You can change values by accessing keys
Example:
person["name"] = "Anjali"
Adding New Items:
person["email"] = anj@gmail.com
Removing Items:
# Using del
del person["city"]
# Using pop()
person.pop("age")
# Using popitem() removes the last inserted key-value
person.popitem()
Looping Through a Dictionary
Example:
person = {
"name": "Anita",
"skills": ["Python", "Django"],
"details": {"age": 28, "city": "Delhi"}
}
for key in person:
print(key)
Loop through values:
for value in person.values():
print(value)
Loop through key-value pairs:
person = {
"name": "Anita",
"skills": ["Python", "Django"],
"details": {"age": 28, "city": "Delhi"}
}
for key, value in person.items():
print(key, ":", value)
print(person.items())
Nested Dictionaries
Dictionaries inside dictionaries (useful for structured data):
Example:
students = {
"student1": {"name": "Ravi", "age": 21},
"student2": {"name": "Neha", "age": 22}
}
print(students["student1"]["name"]) # Output: Ravi
Using in Keyword with Dictionary
Check if a key exists:
if "name" in person:
print("Yes")
Real life use case
inventory = {
"apples": 50,
"bananas": 30,
"oranges": 70
}
# Add new stock
inventory["bananas"] += 20
# Check stock
for fruit, quantity in inventory.items():
print(fruit, ":", quantity)
Dictionary Methods
|
Method |
Description |
|
dict.get(key) |
Returns the value for a key |
|
dict.keys() |
Returns all keys |
|
dict.values() |
Returns all values |
|
dict.items() |
Returns all key-value pairs |
|
dict.update() |
Updates the dictionary with another dict |
|
dict.pop(key) |
Removes the key and returns its value |
|
dict.clear() |
Removes all items |
|
dict.copy() |
Returns a shallow copy |
|
dict.fromkeys() |
Creates a dictionary from keys |
|
dict.setdefault() |
Returns the value of a key; sets if absent |
4.Set – Unordered and Unique
A set is an unordered collection of unique items. It's useful when you want to eliminate duplicates.
Key Features
-
A set does not maintain any specific order of elements.
-
It only stores unique items, automatically removing any duplicates.
-
Sets are mutable, so you can add or remove elements after creation.
-
Elements in a set must be immutable (e.g., numbers, strings, or tuples), but the set itself is mutable.
Example:
colors = {"red", "blue", "green", "red"}
print(colors) #Output: {'red', 'green', 'blue'} – No duplicates
Example:
my_set={1,2,3,4,5}
print(my_set) #Output: {1, 2, 3, 4, 5}
print(type(my_set)) #Output:
Example:
empty_set = set() # Correct
not_a_set = {} # This creates an empty dictionary
Set Methods and Operations
Adding Elements
Example:
s = {1, 2}
s.add(3)
Update (Add Multiple Items)
s.update([4, 5], {6, 7})
print(s) # {1, 2, 3, 4, 5, 6, 7}
print(s) # {1, 2, 3}
Removing Elements
s.remove(3) # Removes 3, raises error if not found
s.discard(10) # Removes 10, no error if not found
Pop Element
s.pop() # Removes a random element
Clear All Elements
s.clear()
Looping Through a Set:
Example:
s={1,2,3}
for item in s:
print(item)
Set Operations
Sets support mathematical set operations, which are useful in many real-world tasks like data filtering, comparison, etc.
1. Union (| or .union())
Returns all unique items from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) #Output : {1, 2, 3, 4, 5}
2. Intersection (& or .intersection())
Common elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) #Output: {3}
3. Difference (- or .difference())
Items in set a but not in set b.
a = {1, 2, 3}
b = {3, 4, 5}
print(a - b) #Output: {1, 2}
4. Symmetric Difference (^)
Items in either set, but not in both.
a = {1, 2, 3}
b = {3, 4, 5}
print(a ^ b) # Output: {1, 2, 4, 5}
Set Comparison Methods
1.issubset()
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # Output: True
2. issuperset()
a = {1, 2}
b = {1, 2, 3}
print(b.issuperset(a)) #Output: True
|
Function |
Description |
|
len(s) |
Returns number of elements in set |
|
max(s) |
Returns max element |
|
min(s) |
Returns min element |
|
sum(s) |
Returns sum of elements |
|
sorted(s) |
Returns sorted list of set items |

