Should you choose Python List or Dictionary, Tuple or Set? The biggest difference between these data structures is their usage:
- Lists - for ordered sequence of objects
- Tuple - can be considered as immutable list
- Python Set - unique list
- Python Dictionary / dict - pair of key and values
The choice depends on several criteria like:
- Item access
- Operations
- Performance
- Looping techniques
- Uniqueness
- Mutability
How to choose? Below you can find short information with code examples and most popular operations for each structure.
List
- Use a list if you have an ordered collection of items or sequence of objects. A list contain elements which are indexed from 0 and can be accessed by this index. Elements can be added, removed and updated. The whole list can be sorted and sliced. Mutable data structure. You can check the operation in the table below:
Set
Elements doesn't have order and duplicates. Big advantage of set is performance - they are extremely fast and has bonus operations like: intersection and union. Set is not hashable. More information here: Unordered collections of unique elements
Examples with sets
# definition
s1=set([1, 2, 3])
s=set()
# add elements
s.add(2)
s.add(3)
one=set([1, 2, 3, 4])
two=set([4, 5, 6, 7])
# union
one.union(two) # {1, 2, 3, 4, 5, 6, 7}
# intersection
one.intersection(two)
one - two # {4}
Tuple
Elements can't be added, removed or replaced after declaration. Tuple is hashable while lists are not. Official docs: Tuples and Sequences
Basic usage of tuples
# definition
s1 = (1, 2, 3, 4)
s2 = ()
s3 = ('a', 0, 3.14)
# operations
s1.count(1) # 1
s1.index(1) # 0
Dictionary
- Use a dictionary when you have pairs of unique keys that map to values and there is a need for efficient look up by key. For dictionaries - there is index of keys - which should be unique. Each key has matching value. There's no ordering for Dictionaries and it's not natural to get first or last element( it might be possible in some situations). You can add, remove or modify values of dictionaries. You can check the operation in the table below:
Below you can find simple table which is going to help you with this choice between List and Dict for Python:
Python List vs Dictionary CheatSheet
Comparison of most popular operation for Python List and Dictionary with examples. Table is perfect for beginners and advanced users and can be used in every day work.
List | Dictionary | |
---|---|---|
Example | [0, 1, 2] | {0: 'Mon', 1: 'Tue'} |
Details | 1. Order is important 2. Items can be repeated 3. Heterogeneous data 4. Slicing |
1. Key : Value pairs 2. Keys should be unique, values not 3. Heterogeneous data 4. Access by key |
When to use | Ordered sequence of items | Associate values with keys |
Declaration | days=['Mon', 'Tue', 'Wed', 'Thu'] | days = { 'Mon': 'Monday', 'Tue': 'Tuesday', 'Wed': 'Wednesday'} |
Add item | days.extend('Fri') - change list days + 'Fri' - produce new list days.append('Fri') days.append(['Fri', 'Sun']) |
days['Thu'] = 'Thursday' |
Item access |
days[0] - first days.index("Mon") - by index days[-1] - last |
1. days['Mon'] 2. days.get('Mon', 'Fri') Python Get First/Last N Items of a Dict |
Get default |
try: day = days[11] except IndexError: day = 'Mon' |
days.get('Mon', 'Fri') |
Update item |
days[0] = 'Monday' | days['Mon'] = 0 |
Remove item |
del days[0] - by index days.remove('Monday') - value |
del days['Mon'] |
Looping Techniques |
for day in days(): print(day) |
for k, v in days.items(): print(k, v) |
Sort | days.sort() | 1. by keys 2. by elements Python How to sort items in dictionary |
Slicing | days[0:3] - start 0, end 2 days[:] - all items days[-1] - last element days[::-1] - reverse list |
dict(itertools.islice(days.items(), 2)) - values |
Compre- hensions |
[x + ' is a day' for x in days] | {i : chr(65+i) for i in range(4)} |
Check item existence |
day in days | 1. value - day in days.values() 2. key - days.get(day) |
Docs | 1. List methods 2. List Comprehensions |
1. Dictionaries 2. Dict Comprehensions |
Performance | Time Complexity List | Time Complexity Dict |