Sunday, 9 November 2025

Summary of Python Collections

Python Collections

Python provides several built-in collection data types that help you store and organize data efficiently.

The four main types are:

Collection Type

Ordered

Mutable

Allows Duplicates

List

Yes

Yes

Yes

Tuple

Yes

No

Yes

Set

No

Yes

No

Dictionary

Yes (Python 3.7+)

Yes

Keys must be unique

List

A list is an ordered, mutable (changeable) collection that can store items of different data types.

# Example of a List
fruits = ["apple", "banana", "cherry"]
print(fruits)            # ['apple', 'banana', 'cherry']

# Add an item to a List
fruits.append("orange")
print(fruits)            # ['apple', 'banana', 'cherry', 'orange']

# Access an item from a List
print(fruits[1])         # banana

Tuple

A tuple is an ordered, immutable collection. Once created, its elements cannot be changed. Use tuples when you need a fixed collection of items.

# Example of a Tuple
colors = ("red", "green", "blue")
print(colors)             # ('red', 'green', 'blue')

# Access an item
print(colors[0])          # red

# Trying to change a value will cause an error
# colors[1] = "yellow"  ❌ (TypeError)

Set

A set is an unordered collection of unique items. Duplicates are automatically removed. Use sets when you need to store unique elements and perform operations like union or intersection.

# Example of a Set
numbers = {1, 2, 3, 3, 4}
print(numbers)           # {1, 2, 3, 4}

# Add an element
numbers.add(5)
print(numbers)           # {1, 2, 3, 4, 5}

# Remove an element
numbers.remove(2)
print(numbers)           # {1, 3, 4, 5}

Dictionary (dict)

A dictionary stores data as key-value pairs. Keys must be unique, and each key maps to a value.

# Example of a Dictionary
student = {
    "name": "Amit",
    "age": 20,
    "course": "CSE"
}

print(student["name"])        # Amit

# Add a new key-value pair
student["grade"] = "A"
print(student)

# Loop through keys and values
for key, value in student.items():
    print(key, ":", value)

Output of Dictionary code:

Amit {'name': 'Amit', 'age': 20, 'course': 'CSE', 'grade': 'A'} name : Amit age : 20 course : CSE grade : A


No comments:

Post a Comment