Python collections are used to store data, for example, lists, dictionaries, sets, and tuples, all of which are built-in collections. Let’s understand and discuss the differences between these built-in collections.
Let’s first see the difference in terms of how we create them.
# Various ways to create a listprint("List Examples")list1=[1,4,"Gitam",6,"college"]list2=[] # creates an empty listlist3=list((1,2,3))print(list1)print(list2)print(list3)# Various ways to create a tupleprint("Tuple Examples")tuple1=(1,2,"college",9)tuple2=() # creates an empty tupletuple3=tuple((1,3,5,9,"hello"))print(tuple1)print(tuple2)print(tuple3)# How to create a setprint("Set Examples")set1={1,2,3,4,5,"hello","tup"}set2={(1,8,"python",7)}print(set1)print(set2)# How to create a dictionaryprint("Dictionary Examples")dict1={"key1":"value1","key2":"value2"}dict2={} # empty dictionarydict3=dict({1:"apple",2:"cherry",3:"strawberry"})print(dict1)print(dict2)print(dict3)
The fundamental distinction that Python makes on data is whether or not the value of an object changes. An object is mutable if the value can change. Otherwise, the object is immutable.
List | Tuples | Sets | Dictionaries |
Lists are mutable | Tuples are immutable | Sets are mutable and have no duplicate elements | Dictionaries are mutable and keys don’t allow duplicates |
Let’s see the code examples to understand their mutability or immutability properties.
# Listsprint("Lists Examples")list1=["hello",1,4,8,"good"]print(list1)list1[0]="morning" # assigning values ("hello" is replaced with "morning")print(list1)# Tuplesprint("Tuples Examples")tuple1=("good",1,2,3,"morning")print(tuple1)print(tuple1[0]) # accessing values using indexing#tuple1[1]="change" # a value cannot be changed as they are immutable# Setsprint("Sets Examples")set1={1,2,3,4,5}print(set1)# print(set1[0]) sets are unordered, so it does not support indexingset1.add(6)print(set1)set2={3,7,1,6,1} # sets does not allow duplicate valuesprint(set2)# Dictionariesprint("Dictionaries Examples")dict1={"key1":1,"key2":"value2",3:"value3"}print(dict1.keys()) # all the keys are printedprint(dict1.values()) # all the values are printeddict1["key1"]="replace_one" # value assigned to key1 is replacedprint(dict1.values()) # all the values are printed
Python has a set of built-in methods that are used on these collections. They are:
Manipulation Operations | Lists | Tuples | Sets | Dictionaries |
Adding | The | An element can’t be added to the tuple as it is immutable | The set | The |
Removing | The | Tuples are immutable | The | The |
Ordering | The | Though tuples are ordered, the elements can’t be sorted | Elements in the set can’t be sorted as they are unordered | The |
Let’s see the code examples to understand the add, remove, and sorting operations on the built-in collections.
# List --- Adding, Removing, Orderingprint("List Examples")list1=["apple","kiwi","banana","grapes"]list1.append("strawberry") # strawberry is added to the listprint(list1)list1.pop() # removes the last element from the listprint(list1)print(list1.sort())# Tuple --- Adding and Removingprint("Tuples Examples")tuple1=(1,2,3,4)# tuple1.pop() tuple cannot be modified# tuple1.append() tuple cannot be modifiedprint(tuple1)# Set --- Adding and Removingprint("Sets Examples")set1={"water","air","food"}set1.add("shelter") # adds an element to the set at random positionprint(set1)set1.add("clothes")print(set1)set1.pop() # removes random element from the setprint(set1)# Dictionary --- Adding, Removing, Orderingprint("Dictionary Examples")dict1={"fruit1":"apple","fruit2":"banana","veg1":"tomato"}dict1.update({"veg2":"brinjal"})print(dict1)dict1.update({"veg3":"chilli"}) # updates the dictionary at the endprint(dict1)dict1.pop("veg2")print(dict1)
If you want to learn how to sort dictionaries in Python, visit this Answer.
Let’s explore the further differences in the operations on lists, tuples, sets, and dictionaries in Python:
Manipulation Operations | Lists | Tuples | Sets | Dictionaries |
Indexing | The | Searches the tuple for a specified value and returns the position of where it was found | The index of a particular element is not retrieved as they are unordered | The |
Counting | The | The | There are no | The |
Reversing | The | The | The sets are unordered, which refrains from applying the | The elements can’t be reversed because the items in the dictionary are in the form of key-value pairs |
Let’s see the code examples to understand how to get index, count, and reverse operations on the built-in collections.
#Listprint("List Examples:")list1=[1,5,3,9,"apple"]print(list1.index(9)) # returns the index value of the particular elementlist2=[2,7,8,7]print(list2.index(7)) # returns the index value of the element at its first occurenceprint(list2.index(7,2)) # returns the index value of the element from the particular start position given#Tupleprint("Tuple Examples:")tuple1=(1,3,6,7,9,10)print(tuple1.index(6))print(tuple1.index(9))#Setprint("Set Examples:")set1={1,5,6,3,9}# set1.index() will throw an error as they are unordered#Dictionaryprint("Dictionary Examples:")dict1={"key1":"value1","key2":"value2"}# dict1.index("key1") will throw an errorprint(dict1.get("key1"))
Understanding the distinctions and characteristics of lists, tuples, sets, and dictionaries in Python empowers developers to select the most suitable data structure for their specific needs. Each offers unique advantages and trade-offs in terms of mutability, ordering, duplication, and retrieval efficiency.