Inbuilt data structures in Python

ยท

11 min read

Inbuilt data structures in Python

Introduction

Data Structures are a way of organizing and storing data in a way so that it can be used efficiently. Knowing inbuilt data structures of any language can save you a lot of time and help you decide better which one to use according to the nature of data. In this blog, I will discuss about some of the important data structures in python and their common operations. ๐Ÿ™‚

List

List is a ordered collection of items which are changeable, and it allows duplicates.

1. Create a list

There are two ways to create a list in a python.

  • Using square [] brackets

    empty_list = []
    marks_list = [98, 92, 93, 91]
    print(empty_list)
    print(marks_list)
    
  • Call python list built-in function

Syntax:- list(iterable). Iterable is an object which you can loop over like lists, tuples, sets, dictionaries, strings etc.

empty_list = list()
marks_list = list((98, 92, 93, 91))
print(empty_list)
print(marks_list)

Both generates the same output.

Output:-

[]
[98, 92, 93, 91]

2. Find length of a list

Python has a built-in function len which can be used to find length of a list.

marks = [99, 95, 93, 98]
list_length = len(marks)
print(list_length)

Output:-

4

3. Access element in a list

List items can be accessed by using the syntax:- list[index]

Negative index can be used to find the element in reverse order.

  • list[-1] -> returns the last element in the list.
  • list[-2] -> returns the second last element in the list. and so on.
fruits_list = ['apple', 'banana', 'orange', 'mango']
print(fruits_list[2])
print(fruits_list[-1])
print(fruits_list[-3])

Output:-

orange
mango
banana

4. Add element to a list

a. using append()

The append function adds an element to the end of the list.

Syntax:- list.append(item_name)

subjects = ['Maths', 'Physics', 'Chemistry']
print(subjects)
subjects.append('Biology')
print(subjects)

Output:-

['Maths', 'Physics', 'Chemistry']
['Maths', 'Physics', 'Chemistry', 'Biology']

b. using insert()

The insert functions add an element at a specified position in a list.

Syntax:- list.insert(index, item_name)

subjects = ['Maths', 'Physics', 'Chemistry']
print(subjects)
subjects.insert(1, 'Biology')
print(subjects)

Output:-

['Maths', 'Physics', 'Chemistry']
['Maths', 'Biology', 'Physics', 'Chemistry']

5. Modify element in a list

fruits_list = ['apple', 'banana', 'orange', 'mango']
print(fruits_list[1])
fruits_list[1] = 'guava'
print(fruits_list[1])

Output:-

banana
guava

6. Remove element from the list

a. using del

Elements can be deleted using the syntax del list[index] It deletes the value at the specified index and do not return any value.

subjects = ['Maths', 'Physics', 'Chemistry', 'Biology']
del subjects[1]
print(subjects)

Output:-

['Maths', 'Chemistry', 'Biology']

b. using pop

pop function deletes the value and returns the deleted value.

  • list.pop() It deletes the last element from the list.

      subjects = ['Maths', 'Physics', 'Chemistry', 'Biology']
      subject_deleted = subjects.pop()
      print(subject_deleted)
      print(subjects)
    

    Output:-

      Biology
      ['Maths', 'Physics', 'Chemistry']
    
  • list.pop(index) It deletes the element from the list at a specified index.
      subjects = ['Maths', 'Physics', 'Chemistry', 'Biology']
      subject_deleted = subjects.pop(1)
      print(subject_deleted)
      print(subjects)
    
    Output:-
      Physics
      ['Maths', 'Chemistry', 'Biology']
    

c. using remove

If we want to remove an element by value and not by index, we can use remove.

subjects = ['Maths', 'Physics', 'Chemistry']
subjects.remove('Physics')
print(subjects)

Ouput:-

['Maths', 'Chemistry']

If the value specified is not valid, it returns a value error.

ValueError: list.remove(x): x not in list

d. using clear

To remove all the elements from the list, you can use the function clear()

subjects = ['Maths', 'Physics', 'Chemistry']
subjects.clear()
print(subjects)
print(len(subjects))

Ouput:-

[]
0

7. Looping through the list

numbers = [5, 6, 3, 22]
for number in numbers:
      print(number)

Another way:-

numbers = [5, 6, 3, 22]
for i in range(0, len(numbers)):
      print(numbers[i])

Ouput (in both the case):-

5
6
3
22

Important Note:-

A python list can contain item of any type:- list, set, tuples, dictionaries, numbers, strings eg:-

sample_list = [1, 'food', [2, 4, 6], {"set_element1", "set_element2"}, {"blog_name": "python DS"}, (1, 2)]
print(sample_list)
for element in sample_list:
    print(type(element))

Output:-

[1, 'food', [2, 4, 6], {'set_element1', 'set_element2'}, {'blog_name': 'python DS'}, (1, 2)]
<class 'int'>
<class 'str'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>

Set

Set is a unordered collection of items which are immutable, and it does not allow duplicates. Set in themself is mutable since we can add and remove element but the elements it consists of must be immutable.

1. Create a set

There are two ways to create a list in a python.

  • Using curly {} brackets
    marks_list = {98, 92, 93, 91}
    print(marks_list)
    

We cannot create empty set using {} brackets, as it would default to dictionary. i.e empty_set = {} would create empty dict instead of empty set. We can use the below method to create an empty set.

  • Call python list built-in function
    empty_set = set()
    numbers_set = set((98, 92, 93, 91))
    # we can put any iterable inside set, like set([98,92,93,91])
    print(empty_set)
    print(numbers_set)
    

Output:-

set()
{98, 91, 92, 93}

2. Find length of a set

Python has a built-in function len which can be used to find length of a set.

numbers = {99, 95, 93, 98, 95}
set_length = len(numbers)
print(numbers)
print(set_length)

Output:-

{98, 99, 93, 95}
4

3. Access element in a set

Since, set elements are unordered, python does not provide any method to access element at some index. But we can check whether the element is present in the set or not using in operator.

fruits_set = {'apple', 'banana', 'orange', 'mango'}
if "apple" in fruits_set:
    print("Apple is present")
else:
    print("Apple is absent")

Output:-

Apple is present

4. Add element to a set

For list, we had an option to insert the element at the end or at some index, but for set there is no such index thing since as I said before, elements are unordered in set. So, we can simply add an element to a set, but can't guarantee at which position it would go to.

Syntax:- set.add(element)

subjects = {'Maths', 'Physics', 'Chemistry'}
print(subjects)
subjects.add('Biology')
print(subjects)

Output:-

{'Physics', 'Chemistry', 'Maths'}
{'Physics', 'Chemistry', 'Biology', 'Maths'}

5. Modify element in a set

Since, sets are unordered, we can't access element at a particular index and modify them.

6. Remove element from the set

a. using pop

pop function deletes the last value and returns the deleted value.

Syntax:- set.pop() It deletes the last element from the list and returns that value.

subjects = {'Maths', 'Physics', 'Chemistry', 'Biology'}
subject_deleted = subjects.pop()
print(subject_deleted)
print(subjects)

Output:-

Maths
{'Chemistry', 'Biology', 'Physics'}

If you execute the above code several times, each time you will get a different output, since elements are unordered in set.

b. using remove

To remove an element by value, we can use function remove(). It does return any value.

subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.remove('Physics')
print(subjects)

Ouput:-

{'Maths', 'Chemistry'}

If the value specified is not valid, it returns a KeyError.

subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.remove('Biology')
print(subjects)
KeyError: 'Biology'

c. using discard

discard is similar to remove except it does return any KeyError on wrong value.

subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.discard('Physics')
print(subjects)

Ouput:-

{'Chemistry', 'Maths'}

In the below example, Biology is invalid value.

subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.discard('Biology')
print(subjects)
{'Maths', 'Physics', 'Chemistry'}

d. using clear

To remove all the elements from the set, you can use the function clear()

subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.clear()
print(subjects)
print(len(subjects))

Ouput:-

set()
0

7. Looping through the elements

numbers = {5, 6, 3, 22}
for number in numbers:
      print(number)

Ouput:-

5
6
3
22

Important Note:-

  • Since, elements in a set cannot be changed, they can be numbers, strings, and tuples, but cannot be lists or dictionaries or sets. i.e only immutable elements are allowed in set.

Dictionary

It is a collection of key-value pairs. A key must be immutable like strings, numbers, tuples. Keys are unique in dictionary. A value can be anything (strings, numbers, tuples, list, sets, dictionary)

1. Create a dictionary

  • Using curly {} brackets

    empty_dict = {}
    subj_marks_dict = {
       "Maths": 98,
       "Chemistry": 92
    }
    print(empty_dict)
    print(subj_marks_dict)
    
  • Call python dict built-in function

    empty_dict = dict()
    subj_marks_dict = dict([("Maths", 98), ("Chemistry", 92)])
    # Some other way
    # subj_marks_dict = dict({"Maths": 98, "Chemistry": 92})
    print(empty_dict)
    print(subj_marks_dict)
    

Both generates the same output.

Output:-

{}
{'Maths': 98, 'Chemistry': 92}

2. Find length of a dictionary

Python has a built-in function len which can be used to find length of a dictionary.

subj_marks_dict = {
     "Maths": 98,
     "Chemistry": 92
}
dict_length = len(subj_marks_dict)
print(list_length)

Output:-

2

3. Access element in a dictionary

Dictionary items can be accessed by using the syntax:- dict[key]

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
print(student["name"])
print(student["college"])

Output:-

Student1
IIT Roorkee

If the key is not valid it throws the KeyError. Using the same dictionary as above.

print(student["branch"])

Output:-

KeyError: 'branch'

Dictionary elements can also be accessed using the get keyword. The difference between square bracket and get is that get doesn't throw error in case of invalid key, instead it prints None.

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
print(student.get("name"))
print(student.get("college"))
print(student.get("branch"))

Output:-

Student1
IIT Roorkee
None

If you don't like None to be printed instead want some default values, you can do so by passing a second argument to get.

print(student.get("branch", "Mechanical"))

Output:-

Mechanical

4. Add new element to the dictionary

A new element can be added to the dictionary just by adding a new key-value pair.

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
student["rollNo"] = 18
print(student)

Output:-

{'name': 'Student1', 'college': 'IIT Roorkee', 'hobbies': ['pool', 'blogging'], 'gender': 'male', 'rollNo': 18}

5. Modify element in a dictionary

You can modify element in a dictionary by specifying a new value to the key.

Syntax:- dict[key] = new_value

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
student["name"] = "Student2"
print(student)

Output:-

{'name': 'Student2', 'college': 'IIT Roorkee', 'hobbies': ['pool', 'blogging'], 'gender': 'male'}

6. Remove element from the dictionary

Elements can be deleted using the syntax del dict[key] It deletes the specified key value pair and do not return any value.

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
del student["hobbies"]
print(student)

Output:-

{'name': 'Student1', 'college': 'IIT Roorkee', 'gender': 'male'}

To remove all the elements from the dictionary, you can use the function clear()

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}
student.clear()
print(student)

Ouput:-

{}

7. Looping through the dictionary

Consider the following dictionary as an example.

student = {
    "name": "Student1",
    "college": "IIT Roorkee", 
    "hobbies": ['pool', 'blogging'],
    "gender": "male"
}

a. looping all key-value pairs

for key, value in student.items():
     print(key, ":", value)

Output:-

name : Student1
college : IIT Roorkee
hobbies : ['pool', 'blogging']
gender : male

b. looping all keys

for key in student.keys():
    print(key)

Output:-

name
college
hobbies
gender

c. looping all values

for value in student.values():
    print(value)

Output:-

Student1
IIT Roorkee
['pool', 'blogging']
male

Important Note:-

  • Python dictionary keys must be immutable while values can be any.
  • The key-value pairs are in the same order that you insert them (application since python 3.7) unlike set, where elements are unordered.

Tuple

A tuple in python is a immutable list, that means we can't add, modify or delete values from the tuple. As a result, we don't have any operations that we see in list.

Why use tuple? A tuple is very useful when we want to create a list that we don't want to change. A tuple can prevent accidental modification, deletion or addition.

1. Creating a tuple

  • Using square [] brackets
    even_numbers = (2, 4, 6, 8, 10)
    print(even_numbers)
    
  • Call python tuple built-in function

Syntax:- tuple(iterable)

even_numbers = tuple([2,4, 6, 8, 10])
print(even_numbers)

Both generates the same output.

Output:-

(2, 4, 6, 8, 10)

2. Find length of a tuple

Python has a built-in function len which can be used to find length of a tuple.

even_numbers = (2,4, 6, 8, 10)
tuple_length = len(even_numbers)
print(tuple_length)

Output:-

5

3. Access element of a tuple

Tuple items can be accessed by using the syntax:- tuple[index]

Negative index can be used to find the element in reverse order.

  • list[-1] -> returns the last element in the list.
  • list[-2] -> returns the second last element in the list. and so on.
even_numbers = (2,4, 6, 8, 10)
print(even_numbers[0])
print(even_numbers[-1])

Output:-

2
10

4. Looping through the tuple

numbers = (5, 6, 3, 22)
for number in numbers:
      print(number)

Another way:-

numbers = (5, 6, 3, 22)
for i in range(0, len(numbers)):
      print(numbers[i])

Ouput (in both the case):-

5
6
3
22

Important Note:-

A python tuple similar to list can contain item of any type:- list, set, tuples, dictionaries, numbers, strings eg:-

sample_list = (1, 'food', [2, 4, 6], {"set_element1", "set_element2"}, {"blog_name": "python DS"}, (1, 2))
print(sample_list)
print(type(sample_list))
for element in sample_list:
    print(type(element))

Output:-

(1, 'food', [2, 4, 6], {'set_element1', 'set_element2'}, {'blog_name': 'python DS'}, (1, 2))
<class 'tuple'>
<class 'int'>
<class 'str'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>

ย