Popular Python Data Structures: Comparison & Operations

Asmath Last Updated : 28 Oct, 2024
4 min read
This article was published as a part of the Data Science Blogathon.

Python is one of the most popular languages for Data Science, and having a strong understanding of its Data Structures is a must for beginners as well as experienced professionals. Even though there are numerous data structures available, only four of them are used approximately 80% of the time.

Lists, Tuples, Dictionaries, and Sets are the Four Horsemen of Data Structures in Python.

Let’s go through their basic characteristics, operations, use cases and understand how they compare to each other.

Lists

Lists are Ordered, Mutable collections of Data, enclosed by square brackets [ ], and use commas to separate their values. They can contain different data types, repeated values and are iterable.

Use Case: Lists are generally used to store similar data which belong to a common category. For example, List of Fruits, List of Students in Class B……and so on.

Let’s create a list of flowers:

Python Code:

flowers = ['Rose', 'Iris', 'Hyacinth', 'Lily', 'Tulip']
print(flowers)

List Operations

Operations such as accessing, adding, modifying, removing, and deleting list elements are illustrated below, with the help of our list of flowers.

  • Accessing Items in a List
# Items can be accessed using Indexing and Slicing

print(flowers[1])      #output: Iris
print (flowers[2:4])   #output: ['Hyacinth', 'Lily']
  • Adding Items to a List
flowers.append('Lotus')           # .append() adds an item to the end of the list

flowers.insert(3,'Magnolia')      # .insert(index,value) adds an item to the index of your choice

flowers.extend(['Jasmine','Carnation'])   # .extend() adds multiple items to the list

#output:  ['Rose', 'Iris', 'Hyacinth', 'Magnolia', 'Lily','Tulip', 'Lotus','Jasmine','Carnation']

  • Removing/Deleting Items in a List
del flowers[1]            # del function deletes items based on Index

flowers.pop(0)            # .pop() too deletes items based on Index

flowers.remove('Lotus')   # .remove() takes the value to be deleted as the argument

#output: ['Hyacinth', 'Magnolia', 'Lily', 'Tulip', 'Jasmine', 'Carnation']
  • Replacing Items in a List
flowers[3]='Orchid' 

 #output: ['Hyacinth', 'Magnolia', 'Lily', 'Orchid', 'Jasmine', 'Carnation']

# You can also use List Comprehension to replace values

flowers=['Daffodil' if i=='Lily' else i for i in flowers]

#output: ['Hyacinth', 'Magnolia', 'Daffodil', 'Orchid', 'Jasmine', 'Carnation']
  • Sorting Items in a List
flowers.sort()   #sorts in ascending order ,for descending use list.sort(reverse = True)

#output: ['Carnation', 'Daffodil', 'Hyacinth', 'Jasmine', 'Magnolia', 'Orchid']
  • Clearing & Deleting a List
#Removing all items from a list

flowers.clear()   #output: []

# Deleting a list

del flowers   #if you enter the list name, an error is returned:
               "NameError: name 'flowers' is not defined"

Tuples

Tuples are Ordered, Immutable collections of Data, and are the default data type in Python. Immutable means that they can’t be modified and items can’t be added or deleted. The data is enclosed in parenthesis ().

Use Case: Tuples are ideal data structures where the data shouldn’t be changed. For example, coordinates i.e. Latitudes and Longitudes of places can be stored in tuples.

Tuple Operations

Operations such as accessing, sorting, and assigning elements in tuples are illustrated below:

Let’s create a tuple of pin codes:

pincodes = (500010, 500045, 500022, 500068, 500034)
  • Accessing elements of a Tuple
# Items can be accessed using Indexing and Slicing

print(pincodes[3])          #output: 500068
print(pincodes[0:4])        #output: (500010, 500045, 500022, 500068)
  • Sorting values
sorted(pincodes)  #sorted returns a new list with sorted values,
                   instead of changing the original tuple
#output: [500010, 500022, 500034, 500045, 500068]
  • Tuple Assignment
#You can assign multiple values to variables at once using tuples

a,b,c=(1,2,3)

print(a)  #output: 1
print(b)  #output: 2
print(c)  #output: 3
  • Concatenation
#Since you can't modify a tuple, simply create a new one

tuple1=(10,20,30)

tuple2= tuple1 + (40,50,60) #concatenation

#output: (10, 20, 30, 40, 50, 60)

Dictionaries

Dictionaries are unordered, Mutable collections of data, where the data is stored in the form of key:value pairs. The values can be accessed directly if their keys are known, without having to iterate over. The data is enclosed in curly brackets. The values can be mutable and repetitive, but keys have to be unique and immutable.

Use Case: Dictionaries are useful when you need instant access to data, without having to iterate over all the values. For example, employee data can be stored in dictionaries.

Let’s create a dictionary:

Employee={'Id':1,'Name':'Tom','Age':30,'Education':'Masters','Department':'IT','Salary':100000}

Dictionary Operations

Operations such as accessing, adding, modifying, removing, and deleting dictionary elements are illustrated below, with the help of our dictionary of employees.

  • Accessing Data
#Accessing Elements
Employee['Name']   #output: Tom

#Finding keys using 'IN' Operator
'Education' in Employee  #output: True

#Viewing Keys 
Employee.keys()  #output: dict_keys(['Id', 'Name', 'Age', 'Education', 'Department', 'Salary'])

#Viewing Values
Employee.values()   #output: dict_values([1, 'Tom', 30, 'Masters', 'IT', 100000])
  • Adding Elements
Employee['Bonus']='Yes'    # Syntax: dictionary['newkey']='value'
  • Deleting Elements
del Employee['Bonus']   #del function

Employee.pop('Salary')  # .pop()

Employee.popitem()      # .popitem() deletes the last element of the dictionary

#output: {'Id': 1, 'Name': 'Tom', 'Age': 30, 'Education': 'Masters'}
  • Clearing & Deleting a Dictionary
Employee.clear()    #output: {}

del Employee       #deletes the dictionary

Sets

Sets are unordered, mutable collections of data, which can’t contain repeated values. They can take different data types, and are enclosed by curly braces {}.

Use Case: Sets are helpful for performing mathematical operations on the data, and when you need to store distinct values.

Let’s create a Set of Genres:

Genres= {"Fiction", "NonFiction", "Drama", "Poetry"}
#output: {'Drama', 'Fiction', 'NonFiction', 'Poetry'}  #notice how sets are sorted automatically

Set Operations

 Adding, removing and mathematical operations on sets are illustrated below:

  • Adding Items to a Set
Genres.add("Folktale")

#Adding Multiple Items

Genres.update(['Horror','Distopian','SciFi'])

#output: {'Distopian','Drama','Fiction','Folktale','Horror','NonFiction','Poetry','SciFi'}
  • Removing Items from a Set
Genres.remove("Poetry")       # .remove() deletes an item, and raises an Error 
                                 if it doesn't already exist in the set
Genres.discard("Thriller")    # .discard() deletes an item in a set, 
                                 but in case the item doesn't exist, it doesn't return an error
  • Mathematical Operations on Sets
#Let's create two sets

Set1={1,2,3,4,5}
Set2={4,5,6,7,8}

#Intersection

Set1 & Set2              #Use '&' for intersection
#output: {4, 5}

Set1.intersection(Set2)  # or use .intersection() to find common elements

#Union

Set1.union(Set2)  
#output: {1, 2, 3, 4, 5, 6, 7, 8}

#Let's create another Set

Set3={1,2,3}

#Subset

Set3.issubset(Set1)              #check if subset
#output: True         

#Superset

Set1.issuperset(Set3)    #check if superset
#output: True

#Difference

Set1.difference(Set2)     # finds how different Set1 is from Set2 
#output: {1, 2, 3}

 

Conclusion:

Knowledge of the fundamental Data Structures discussed above is essential for carrying out Data Science & Analytics operations. Each Data Structure has its own advantages and disadvantages. The choice of Data Structure depends on the type and nature of the data one is dealing with, and the operations intended to be performed on the data.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details