Difference between tuple, list and dictionary
n Python, there are 3 types of collections, tuples, lists and dictionaries. There is alot of confusion about what they are and how and when to use them. We will go through each of the types below.
Tuples
Tuples are immutable and cannot be changed. They are usually heterogeneous and consist of different data types. Tuples are sorted by index and you can get value at any index. Tuples can be used as keys for dictionaries ( which we will see later ). Tuples are declared with parenthesis in Python. In Python, you can add to a tuple but will end up with a different ID. The following code illustrates this, notice the id of the tuple has changed.
a = (1,2) b = [1,2] id(a) # 140230916716520 id(b) # 748527696 a += (3,) # (1, 2, 3) b += [3] # [1, 2, 3] id(a) # 140230916878160 id(b) # 748527696
Lists
Lists are homogeneous and consist of the same data type. Lists are sorted by index and unlike tuples, lists can change. You can add to a list by making use of the append method:
a.append('foobar')
You can change the value in the list at any index by doing the following:
a[2] = 'foobar'
You can also delete from a list using the del method:
del a[2]
Dictionary
Dictionaries are key value pairs, instead of an index, one accesses it by key. Dictionaries are mutable and can be edited, added to and remove from. Dictionaries are not sorted.