0% found this document useful (0 votes)
10 views

Python Collections

The document provides an overview of Python's collection modules, detailing the characteristics and methods of tuples, sets, lists, and dictionaries. It explains the differences between these data structures, including their mutability, order, and handling of duplicates. Additionally, it offers practical examples of various methods for each collection type to illustrate their usage.

Uploaded by

rajavelujansi
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)
10 views

Python Collections

The document provides an overview of Python's collection modules, detailing the characteristics and methods of tuples, sets, lists, and dictionaries. It explains the differences between these data structures, including their mutability, order, and handling of duplicates. Additionally, it offers practical examples of various methods for each collection type to illustrate their usage.

Uploaded by

rajavelujansi
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
You are on page 1/ 7

Python Collection Modules:

The collection Module in Python provides different types of containers. A Container is an object
that is used to store different objects and provide a way to access the contained objects and iterate over
them.

Python Collections
Python provides several built-in data structures that help in storing and managing data efficiently.
These data structures are categorized into primitive and non-primitive (collection data types).

Tuple:
A tuple in Python is an ordered collection of elements, meaning that the sequence in which items
are stored in the tuple is preserved. When you access elements using indexing, they always appear in the
same order as they were defined.

Note: Tuples Are Immutable but Still Ordered:


 Unlike lists, tuples cannot be modified after creation, but their order remains fixed.
 If you need a different order, you must create a new tuple with the reordered values.

Tuples in Python have limited built-in methods compared to lists because they are immutable (cannot
be modified). However, here are some essential tuple methods and functions useful for problem-solving:

1.count() – Counts the occurrences of an element


t = (1, 2, 2, 3, 4, 2, 5)
print(t.count(2)) # Output: 3

2. index() – Finds the first occurrence of an element


t = ('apple', 'banana', 'cherry', 'banana')
print(t.index('banana')) # Output: 1

3. len() – Finds the length of the tuple


t = (10, 20, 30, 40)
print(len(t)) # Output: 4

4. max() and min() – Find the largest and smallest values


t = (3, 1, 4, 1, 5, 9)
print(max(t)) # Output: 9
print(min(t)) # Output: 1
5. sum() – Calculates the sum of elements
t = (1, 2, 3, 4, 5)
print(sum(t)) # Output: 15

6. sorted() – Sorts the tuple (returns a list)


t = (3, 1, 4, 1, 5, 9)
print(sorted(t)) # Output: [1, 1, 3, 4, 5, 9]
👉 Since tuples are immutable, sorting creates a new list.

7. tuple() – Converts a list or string to a tuple


lst = [1, 2, 3]
print(tuple(lst)) # Output: (1, 2, 3)
s = "hello"
print(tuple(s)) # Output: ('h', 'e', 'l', 'l', 'o')

8. Packing & Unpacking Tuples


a, b, c = (10, 20, 30)
print(a, b, c) # Output: 10 20 30
👉 Useful for swapping values and returning multiple values from functions.

SET:
Sets in Python are unordered, mutable (modifiable), and unique collections. Unlike tuples, sets
do not maintain insertion order and do not allow duplicate values.
1. add() – Adds an element to the set
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}

2. remove() vs discard() – Removes an element


s = {1, 2, 3, 4}
s.remove(2) # ✅ Removes 2
print(s) # Output: {1, 3, 4}
s.remove(10) # ❌ KeyError if element is not present
✅ Alternative: Use discard() to avoid errors if the element is not found.
s.discard(10) # ✅ No error even if 10 is not in the set

3. pop() – Removes and returns a random element


s = {10, 20, 30, 40}
print(s.pop()) # Output: Random element, e.g., 10
print(s) # Remaining elements

4. clear() – Removes all elements


s = {1, 2, 3}
s.clear()
print(s) # Output: set()

5. union() – Combines two sets (removing duplicates)


s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1.union(s2)) # Output: {1, 2, 3, 4, 5}
✅ Shortcut: |
print(s1 | s2) # Same output as union()

6. intersection() – Finds common elements


s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1.intersection(s2)) # Output: {3, 4}
✅ Shortcut: &
print(s1 & s2) # Same output as intersection()

7. difference() – Finds elements in one set but not in the other


s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1.difference(s2)) # Output: {1, 2} (Only in s1)
✅ Shortcut: -
print(s1 - s2) # Same output as difference()
8. symmetric_difference() – Finds elements in either set but not both
print(s1.symmetric_difference(s2)) # Output: {1, 2, 5, 6}
✅ Shortcut: ^
print(s1 ^ s2) # Same output as symmetric_difference()

List:
A list in Python is a mutable, ordered, and indexed collection that allows duplicate values. Lists are
one of the most commonly used data structures in Python due to their flexibility and efficiency.

append() vs. extend() Side-by-Side


lst1 = [1, 2, 3]
lst2 = [4, 5]

lst1.append(lst2)
print(lst1) # Output: [1, 2, 3, [4, 5]]

lst3 = [1, 2, 3]
lst3.extend(lst2)
print(lst3) # Output: [1, 2, 3, 4, 5]
✅ append() keeps the entire list as a single element. Adds entire thing as it is without unpacking.
✅ extend() unpacks and adds elements one by one.

2. insert() – Insert an element at a specific position


lst = [1, 2, 4]
lst.insert(2, 3) # Insert 3 at index 2
print(lst) # Output: [1, 2, 3, 4]
👉 Use case: When the position of insertion is important.

3. remove() – Remove the first occurrence of an element


lst = [1, 2, 3, 2, 4]
lst.remove(2) # Removes first 2
print(lst) # Output: [1, 3, 2, 4]
4. pop() – Remove and return an element (default: last element)
lst = [10, 20, 30]
removed = lst.pop() # Removes and returns 30
print(lst) # Output: [10, 20]
print(removed) # Output: 30
✅ With index:
lst.pop(0) # Removes first element
👉 Use case: When you need to remove an element and use its value.

5. clear() – Remove all elements


lst = [1, 2, 3]
lst.clear()
print(lst) # Output: []
👉 Use case: When you need to reset the list.

6. index() – Find the position of an element


lst = [10, 20, 30, 40]
print(lst.index(30)) # Output: 2
👉 Use case: Finding where an element appears in a list.

7. count() – Count occurrences of an element


lst = [1, 2, 2, 3, 3, 3]
print(lst.count(3)) # Output: 3
👉 Use case: Useful in statistics and frequency analysis.

8. reverse() – Reverse the list in place


lst = [1, 2, 3]
lst.reverse()
print(lst) # Output: [3, 2, 1]
👉 Use case: When you need a list in reverse order.

9. sort() – Sort elements in ascending order


lst = [3, 1, 4, 2]
lst.sort()
print(lst) # Output: [1, 2, 3, 4]
✅ Descending order:
lst.sort(reverse=True)
print(lst) # Output: [4, 3, 2, 1]
👉 Use case: When you need to order numerical or alphabetical data.

10. copy() – Create a shallow copy


lst = [1, 2, 3]
new_lst = lst.copy()
print(new_lst) # Output: [1, 2, 3]

Dictionary:
A dictionary in Python is an unordered, mutable, and indexed collection that stores key-value
pairs. Unlike lists, which use integer indices, dictionaries allow us to access values using unique keys.
Dictionary Methods
🔹 1. keys() – Get all keys
student = {"name": "Alice", "age": 21, "course": "CS"}
print(student.keys()) # Output: dict_keys(['name', 'age', 'course'])

🔹 2. values() – Get all values


print(student.values()) # Output: dict_values(['Alice', 21, 'CS'])

🔹 3. items() – Get key-value pairs as tuples


print(student.items()) # Output: dict_items([('name', 'Alice'), ('age', 21), ('course', 'CS')])

🔹 4. get() – Access a value safely


print(student.get("name")) # Output: Alice
print(student.get("grade")) # Output: None (avoids KeyError)

🔹 5. update() – Merge two dictionaries


student.update({"age": 22, "grade": "A"})
print(student) # Output: {'name': 'Alice', 'age': 22, 'course': 'CS', 'grade': 'A'}

🔹 6. pop() – Remove a key and return its value


age = student.pop("age")
print(age) # Output: 22
print(student) # Output: {'name': 'Alice', 'course': 'CS', 'grade': 'A'}

7. popitem() – Remove and return the last inserted key-value pair


print(student.popitem()) # Output: ('grade', 'A')

8. clear() – Remove all items


student.clear()
print(student)

Summary: List vs. Tuple vs. Set vs. Dictionary

Feature List Tuple Set Dictionary

Ordered? ✅ Yes ✅ Yes ❌ No ✅ (Python 3.7+)

Mutable? ✅ Yes ❌ No ✅ Yes ✅ Yes

Duplicates? ✅ Yes ✅ Yes ❌ No ✅ Keys Unique

Index-Based? ✅ Yes ✅ Yes ❌ No ❌ No (Uses Keys)

Sorting? ✅ Yes ✅ Yes ✅ (after conversion) ✅ (Keys/Values)

Use Case Sequential Data Immutable Data Unique Items Key-Value Lookup

Final Thought

✅ Use Lists when order and duplicates matter.


✅ Use Tuples when immutability is required.
✅ Use Sets when only unique values are needed.
✅ Use Dictionaries for fast lookups and key-value storage.

You might also like