Python Collections - A Quick Comparison
Tags: python, beginners, codenewbie
Published: 2020-06-25 10:34:13

Collections are fundamental ways to store and organize data. There are four basic types of collections available in Python - `tuples`, `lists`, `dictionaries` and `sets`. To become proficient in Python programming, developers should know basic differences between these data structures so they can choose the appropriate type of collection for a given job on hand.  

Below table shows side-by-side comparison of different Python  collections:
<table>
<tr>
<th></th><th>Tuple</th><th>List</th><th>Dictionary</th><th>Set</th>
</tr>
<tr>
<th>Eample</th><td>('Book 1', 12.99)</td><td>['apple', 'banana', 'orange']</td><td>{'name': 'Joe', 'age': 10}</td><td>{10, 20, 12}</td>
</tr>
<tr>
<th>Mutable?</th><td>Immutable</td><td>Mutable</td><td>Mutable</td><td>Mutable</td>
</tr>
<tr>
<th>Ordered?</th><td>Ordered</td><td>Ordered</td><td>Preserves order since Python 3.7</td><td>Unordered</td>
</tr>
<tr>
    <th>Iterable?</th><td>Yes (takes linear time)</td><td>Yes (takes linear time)</td><td>Yes (constant time)</td><td>Yes (constant time)</td>
</tr>
<tr>
    <th>Use case</th><td>Immutable data</td><td>Data that needs to change</td><td>Key/Value pairs</td><td>Unique items</td>
</tr>
</table>

<h4>Common Methods</h4>
It is also quite important to remember some of the common methods available for each collection. This will help in certain circumstances such as interviewing process.
<table>
<tr>
<th>Collection</th><th>Common Methods</th>
</tr>
<tr>
<th>Tuple</th><td>my_tuple[0], len(my_tuple), .count(), .index()</td>
</tr>
<tr>
<th>List</th><td>my_list[0], len(my_list), .count(), .index(), .append(), .insert(), .pop(), .remove(), .reverse(), .sort()</td>
</tr>
<tr>
<th>Dictionary</th><td>d['key'], .keys(), .values(), .items(), .pop(), del d['key']
</td>
</tr>
<tr>
<th>Set</th><td>len(my_set), .add(), .update(), .remove(), .union(), .intersection() and other set operation methods</td>
</tr>
</table>

<h4>Common Methods - Tuple</h4>
```python
t = ('Book 1', 12.99)
# Get the value element for the supplied index, returns IndexError for invalid index  
print(t[1])   # 12.99
# Get length of a tuple
print(len(t))  # 2
# Get index of a given value, if the supplied value is not found,  returns value error
print(t.index('Book 1')) # 0
# Count number of items a given value is present in the collection
print(t.count(12))  # 0
```

<h4>Common Methods - List</h4>
```python
my_list = ['apple', 'banana', 'orange']
# get element present in the specified index
print(my_list[1])  # banana
# find length of the list
print(len(my_list))  # 3
# get index of specified value
print(my_list.index('orange')) # 2
# count number of items times a specified value is present in the collection
print(my_list.count('banana'))  # 1
# adds item to the end of the list
my_list.append('pear')  
# adds item in the specified index
my_list.insert(1, 'grapes')
# removes and returns item from the end of the list
print(my_list.pop())   # pear
# removes specified value from the list
my_list.remove('banana')
# reverses the list
my_list.reverse()
print(my_list)   # ['orange', 'grapes', 'apple']
# sorts the list
my_list.sort()
print(my_list)   # ['apple', 'grapes', 'orange']
``` 

<h4>Common Methods - Dictionary</h4>
```python
d = {'name': 'Joe', 'age': 10}
# returns value of specified key
print(d['name'])  # Joe
# returns length of a dictionary
print(len(d))  # 2
# returns iterable list of keys
print(d.keys())  # dict_keys(['name', 'age'])
# returns iterable list of values
print(d.values()) # dict_values(['Joe', 10])
# returns iterable list of key / value pairs
print(d.items()) # dict_items([('name', 'Joe'), ('age', 10)])
# deletes given key from the dictionary
del d['age']
print(d)   # {'name': 'Joe'}
```

<h4>Common Methods - Set</h4>
```python
s1 = {10, 20, 12}
s2 = {100, 21, 12, 35, 40}
# finds length of a given set
print(len(s2))  # 5
# adds an element to the set, ignored if the element already exists
s1.add(21) 
# updates set with elements of another set
s1.update({33, 30})
# removes specified element from the set, throws KeyError if given element is not in the set
s1.remove(33)
# returns a new set containing all elements from both sets 
print(s1.union(s2))  # {33, 35, 100, 40, 10, 12, 20, 21, 30}
# returns a new set containing common elements from both sets
print(s1.intersection(s2))   # {12, 21}
```