Python Data Structures
List, Dictionary, Set and Tuple
Get Kavisha Nethmini’s stories in your inbox
Join Medium for free to get updates from this writer.
Data structures are essential in Python because they help us to organize and manage data efficiently. During my journey of learning python I explore four main data structures. List, Dictionary, Set and Tuple. Each structure has unique features and useful in different situations.
List
This is a ordered collection that can store different types of data. Biggest advantage is values can be changed after creation that means this is mutable.
my_list = [1,2,"Kavi", ["aa", "bb"]]List Comprehension — Shorter way to create lists
squares = [] OUTPUT -
for i in [1, 2, 3, 4, 5]: [1,4,9,16,25]
squares.append(i * i)squares = [i * i for i in [1, 2, 3, 4, 5]] OUTPUT - [1,,4,9,16,25]Dictionary
Unlike list the dictionaries are use keys instead of indexes. This is also mutable.
my_dictionary = {"x": 1, "y": 2, "z": 3}a = {} we can interpret this as both dictionary and set but this is always a dictionary. Why is that This design choice exists because dictionaries are commonly created using key-value pairs. Therefore, Python treats as an empty dictionary by default. If we want to create an empty set, we must use the a = set() format
Set
Set is an unordered collection of unique elements. Special feature is it automatically remove the duplicates and print the set and we can do all the set operations.
numbers = {1, 2, 3, 3, 4, 4, 5}
print(numbers)Tuple
Tuple is similar to the list but can not be modified after creation
my_tup = (1, 2, 3, 4, 5)
print(my_tup)Since tuples are immutable, we can only do is convert tuple into a list, modify it and then convert back to tuple.
my_tuplist = list(my_tup)
my_tuplist.append(6)
my_tup = tuple(my_tuplist)





