Hello Friends,
Python Collections: Lists, Tuples, Sets, and Dictionaries
Python provides built-in collection data types that allow storing multiple values in a single variable. The most commonly used collections are List, Tuple, Set, and Dictionary.
1. Python List
A list is an ordered, mutable (changeable) collection that allows duplicate values.
Syntax
list_name = [item1, item2, item3]
Example
fruits = ["apple", "banana", "mango"] print(fruits)
Accessing List Items
print(fruits[0])
Modifying List
fruits[1] = "orange" print(fruits)
Common List Methods
fruits.append("grapes")
fruits.remove("apple")
fruits.sort()
print(fruits)
Real-Life Example
marks = [65, 72, 80] total = sum(marks) print(total)
2. Python Tuple
A tuple is an ordered, immutable (cannot be changed) collection.
Syntax
tuple_name = (item1, item2, item3)
Example
colors = ("red", "green", "blue")
print(colors)
Accessing Tuple Items
print(colors[1])
Why Use Tuple?
- Data safety (cannot be modified)
- Faster than lists
Real-Life Example
coordinates = (10.5, 20.3) print(coordinates)
3. Python Set
A set is an unordered collection that does not allow duplicate values.
Syntax
set_name = {item1, item2, item3}
Example
numbers = {1, 2, 3, 3, 4}
print(numbers)
Adding and Removing Elements
numbers.add(5) numbers.remove(2) print(numbers)
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
print(a.intersection(b))
Real-Life Example
emails = {"a@gmail.com", "b@gmail.com", "a@gmail.com"}
print(emails)
4. Python Dictionary
A dictionary stores data in key-value pairs.
Syntax
dict_name = {key1: value1, key2: value2}
Example
student = {"name": "Amit", "age": 21, "course": "Python"}
print(student)
Accessing Dictionary Values
print(student["name"])
Modifying Dictionary
student["age"] = 22 student["city"] = "Delhi" print(student)
Loop Through Dictionary
for key, value in student.items():
print(key, ":", value)
Real-Life Example
employee = {
"id": 101,
"name": "Ravi",
"designation": "Tester",
"salary": 50000
}
print(employee)
Difference Between List, Tuple, Set, Dictionary
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | Yes |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Yes | Yes | No | Keys: No |
Common Mistakes
- Using index on set
- Trying to modify tuple
- Duplicate keys in dictionary
Summary
- Lists are flexible and commonly used
- Tuples are immutable and safe
- Sets remove duplicates
- Dictionaries store structured data
How to Store Ordered and Unique Data in Python
Sometimes we need a data structure that:
- Maintains insertion order
- Does not allow duplicate values
Python does not provide a built-in data type that fully satisfies both conditions. However, there are effective ways to achieve this.
Option 1: Using List with Manual Duplicate Check (Most Common)
A list maintains order but allows duplicates. We can manually prevent duplicates.
items = []
data = ["apple", "banana", "apple", "mango"]
for item in data:
if item not in items:
items.append(item)
print(items)
Output:
['apple', 'banana', 'mango']
Explanation:
The list preserves order and avoids duplicates by checking before inserting.
Option 2: Using OrderedDict (Best Practice)
OrderedDict from the collections module preserves insertion order and removes duplicates.
from collections import OrderedDict data = ["apple", "banana", "apple", "mango"] result = list(OrderedDict.fromkeys(data)) print(result)
Output:
['apple', 'banana', 'mango']
Why This Is Best:
- Preserves order
- Automatically removes duplicates
- Clean and readable
Option 3: Using dict (Python 3.7+)
Since Python 3.7, dictionaries preserve insertion order.
data = ["apple", "banana", "apple", "mango"] result = list(dict.fromkeys(data)) print(result)
Output:
['apple', 'banana', 'mango']
Note:
This is the most commonly used modern Python approach.
Why Not Use Set?
data = ["apple", "banana", "apple", "mango"] print(set(data))
Output (order not guaranteed):
{'banana', 'apple', 'mango'}
Sets remove duplicates but do NOT preserve order.
Comparison Table
| Approach | Ordered | No Duplicates | Recommended |
|---|---|---|---|
| List + Check | Yes | Yes | Good |
| OrderedDict | Yes | Yes | Best |
| dict.fromkeys() | Yes | Yes | Best (Modern) |
| Set | No | Yes | No |
Real-Life Example
Removing duplicate email IDs while keeping order:
emails = [ "a@gmail.com", "b@gmail.com", "a@gmail.com", "c@gmail.com" ] unique_emails = list(dict.fromkeys(emails)) print(unique_emails)
Summary
- No direct built-in ordered set in Python
- Use
dict.fromkeys()for best results - Use
OrderedDictfor clarity - Do not use set when order matters
No comments:
Post a Comment