Comparing Python's Built-in Data Structures: Lists vs Sets vs Dictionaries
Learn the basics and differences between Python's lists, sets, and dictionaries with simple examples and practical uses.
Python offers several built-in data structures that help you store and organize data efficiently. Among the most commonly used are lists, sets, and dictionaries. Each one serves different purposes and has unique characteristics. This guide will compare these data structures, show you when to use each one, and provide simple code examples.
### Lists Lists are ordered collections that can hold any type of element. They allow duplicates and are indexed, which means you can access elements using their position. Lists are ideal when you need to maintain order and access elements by index.
fruits = ['apple', 'banana', 'cherry']
print(fruits[1]) # Output: banana
fruits.append('orange')
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']### Sets Sets are collections of unique elements without any particular order. They are useful when you want to ensure no duplicates and do not care about the order of items. Sets support mathematical operations like union, intersection, and difference.
unique_numbers = {1, 2, 3, 2, 1}
print(unique_numbers) # Output: {1, 2, 3}
# Adding elements
unique_numbers.add(4)
print(unique_numbers) # Output: {1, 2, 3, 4}### Dictionaries Dictionaries store key-value pairs and are unordered (in Python 3.7+, they maintain insertion order). They allow fast lookup of values based on unique keys. Use dictionaries when you need to associate values with specific identifiers.
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print(student_grades['Bob']) # Output: 92
# Adding or updating a value
student_grades['Dave'] = 88
print(student_grades)### Key Differences - Lists allow duplicates and keep the order. - Sets do not allow duplicates and have no order. - Dictionaries store key-value pairs and allow fast access via keys. ### When to Use Each - Use **lists** for ordered collections or when duplicates matter. - Use **sets** to store unique items and perform set operations. - Use **dictionaries** when you need to associate values with keys for quick lookups.
Understanding these differences will help you select the right data structure for your programs and write efficient Python code.