Python Basic – Important Data Structures in Python (Dictionary, Tuple, List)

Home /

Table of Contents

Important Data Structure

Some of the data types have been discussed in the previous sections with proper examples and descriptions, or they have been left out of context. For example, “string” has been identified and used in discussions of print and input/output. The for loop, while loop has been discussed in a relevant way. Since the list is a basic iterable.

This section discusses some of the more important datatypes mentioned below:

  • None
  • Dictionary
  • Dictionary Function
  • Tuple
  • List

None Type

Well, we know which variable data can be stored. Or there can be empty values like empty strings. But if there is no variable that has no value, how can it be initialized? None is an object of NoneType that can actually determine the absence of value.

If I look at the output of the following line –

   >>> type(None)
   <class 'NoneType'>
   >>>

Other data types may have multiple values such as – bool type may have two values; True or False. The only value of NoneType is this None.
None does not mean False. Again, this means 0, ” “, [ ] not even that. Let’s see the comparison and the output below –

   >>> None == False
   False
   >>> None == None
   True
   >>> None == ""
   False
   >>> None == []
   False
   >>> None == 0
   False
   >>> P = None
   >>> P == None
   True
   >>> print(P)
   None
   >>>

When a function specifies something that does not return, it actually returns None. The return of such a function can be seen by checking –

Example:

   def run():
       print("EnableGeek is Awesome")
 
   my_return_value = run()
   print(my_return_value)

Output:

   EnableGeek is Awesome
   None

Another nice use of None is when we define the default value of the function as the default value. Let’s look at the following example –

Example:

   def run(P):
       if P:
           return P * P
       else:
           return 0
 
   print(run())

Output:

Traceback (most recent call last):
 File "/home/tuhin/Desktop/Problem-Solving/Python/python_basic_11.py", line 7, in <module>
   print(run())
TypeError: run() missing 1 required positional argument: 'P'

One of its parameters has also been defined while defining the run() function above. Again, we have logically checked that – if P has a value, it will return square and if not, it will return zero. So when this function is being called we get an error where it is said that the function takes an argument but we do not send it anything.
By modifying this function a little, we can select None as the value of its default argument. This way, when a valid argument is sent when calling this function, the function will work with that valid value and if not, there is no problem – then it will send zero.

Example:

   def run(x = None):
       if x:
           return x * x
       else:
           return 0
 
   print(run())
   print(run(38))

Output:

   0
   1444

In the above program, the function has been called without passing an argument once and has been called another time by sending an argument. Twice working properly.

Dictionary

Earlier we learned about lists which is a type of data structure in which the elements are sorted by sequential index. Dictionary is another type of data structure in which various elements or objects like lists can be stored – however, in that case those elements have to be indexed manually. In other words, we have to assign ourselves a key or index for each element or value. Then a collection of elements with a key-value pair is created.
A dictionary can be created by creating a key-value pair with a colon sign between two curly brackets { } and by separating each pair with a comma. Do the following –

Example:

   Salary = {"May": 20000, "June": 50000, "July": 80000}
   print(Salary["June"])

Output:

   50000

The rules for accessing each element of the dictionary are the same as the list. Just as the value of the index could be found with the index in the third bracket in the list, so also the value associated with it can be accessed by using the key in place of the index.

To create a blank dictionary again, just type it like this and it becomes initialized – my_dictionary = { }

Rules of key-value

Any type of object or element can be stored in the dictionary, only its keys must be Immutable type. A dictionary can be created as follows –

Example:

   Quantity = {
       "Phone" : [3, 5, 2],
       "Laptop" : [54, 12, 61],
       "Tablet": [38, 83, 29]
       }
   print(Quantity["Laptop"])

Output:

  [54, 12, 61]

Among the objects we have discussed so far, lists and dictionaries are of the Mutable type.

Dictionary function

Just as a new value could be set in a specific index in Python’s list, so in the case of a dictionary, a new value can be set by updating any value in a key. Such as –

Example:

   numbers = [12, 14, 16, 17]
   numbers[3] = 8
 
   print(numbers)

Output:

   [12, 14, 16, 8]

In the case of dictionaries –

Example:

 
   numbers = {1 : 10, 2 : 40, 3 : 90, 4 : "EnableGeek"}
   numbers[4] = 100
 
   print(numbers)

Output:

   {1: 10, 2: 40, 3: 90, 4: 100}

In this case, the list and the dictionary behave the same. But in the case of a list, a new index and its value cannot be added manually. Such as –

Example:

   numbers = [32, 44, 56, 68]
   numbers[4] = 50

Output:

    Traceback (most recent call last):
   	File 
      "/home/tuhin/Desktop/Problem-Solving/Python/python_basic_12.py",
      line 3, in <module>
       numbers[4] = 50
   IndexError: list index out of range

That is, although the index of my_list = [32, 44, 56, 68] is up to 3 and we tried to manually add a new value to the fourth index, but it was not possible. This is because the index of the list is created automatically once and thus cannot be indexed manually. Instead append is used.

But if you want, you can manually add a new key to the dictionary and add it to another list with a value. Such as –

Example:

   numbers = {1 : 11, 2 : 44, 3 : 99, 4 : 16}
   numbers[5] = 52
 
   print(numbers)

Output:

   {1: 11, 2: 44, 3: 99, 4: 16, 5: 52}

This means that both the new key 5 and its value 52 have been added manually to the numbers dictionary.

Key search

If we want to check if there is a specific key in a dictionary then in and not in can be used. It is better to say, in this way, but also in the case of the list can be checked. Example –

Example:

   numbers_value = {1: "EnableGeek", 2: "is", 3: "awesome!",}
 
   print(1 in numbers_value)
   print("EnableGeek" in numbers_value)
   print(4 not in numbers_value)

Output:

   True
   False
   True

Use of get

Above we have seen that for accessing data from a dictionary, it is possible to use an index or a key just like a list. But there is a little difficulty in accessing data in this way. Such as –

Example:

   numbers = {1 : 11, 2 : 44, 3 : 99, 4 : 16}
   print(numbers[5])

Output:

   Traceback(most recent call last):
       File 
       "/home/tuhin/Desktop/Problem-Solving/Python/python_basic_12.py", 
       line 3, in <module >
       print(numbers[5])
   KeyError: 5

This means that trying to access data with a key that is not in the dictionary in question will create an unwanted error that can shut down the program. So the best practice is to use the get method. As follows –

Example:

   numbers = {1 : 11, 2 : 44, 3 : 99, 4 : 16}
   print(numbers.get(5))

Output:

   None

That is, the error will not be created, but will return None. Even if you want the default value can be found if the key is not in that dictionary. Such as –

Example:

   numbers = {1 : 11, 2 : 44, 3 : 99, 4 : 16}
 
   print(numbers.get(5, "5 is lost from the dictionary!"))

Output:

  5 is lost from the dictionary!

Tuple

The tuple is another data structure similar to the list already seen. But the important difference is that it is of Immutable type i.e. its value cannot be changed. Again, lists can be created with two [ ] brackets but with a tuple ( ) (although you can create a tuple by separating the values ​​with only a comma without the brackets). There are other differences, and of course, there are reasons why tuples should be used in some places without using lists. They will be discussed here. Such as –

Example:

   types = ("Teacher", "Student", "Worker")  
   print(types[0])
   # or
   types = "Teacher", "Student", "Worker"
   print(types[0])

Output:

   Teacher
   Teacher

We can see that the index can be used just like the list for accessing the value from the top. But new values like lists cannot be added or updated. Such as –

Example:

   types = ("Teacher", "Student", "Worker")  
   types[0] = "Advisor"
   print(types[0])

Output:

Traceback(most recent call last):
   File "/home/tuhin/Desktop/Problem-Solving/Python/python_basic_12.py",
   line 169, in <module >
   types[0] = "Advisor"
TypeError: 'tuple' object does not support item assignment

In a very normal way types=( ) thus a tuple can be initialized.

A tuple can contain another list, dictionary, or tuple as a value. Such as –

Example:

   types = (("Teacher", "Student", "Worker") , ("Driver", "Tester"), [13,
   25, 63], {"Content": "Python"})
   print(types[0][2])
   print(types[1][1])
   print(types[2][0])
   print(types[3]["Content"])

Output:

   Worker
   Tester
   13
   Python

Tuple unpacking

Tuple Unpacking allows each value in a tuple (or any iterable) to be assigned to a separate new variable by typing a line code. Let’s look at the example below,

Example:

   numbers = (11, 22, 33)
   P, Q, R = numbers
   print(P)
   print(Q)
   print(R)

That is, the three values of the tuple named numbers are stored in the next line in three different variables P, Q, and R.

Output:

   11
   22
   33

If it happens that a tuple or iterable has innumerable values but we want to store them in a few different variables. That is, if you do not want to write a number of variables to the left of the equivalent symbol, you can store any remaining number in it by adding * in front of any variable as below,

Example:

   P, Q, *R, S = [51, 52, 53, 54, 55, 56, 57, 58, 59]
   print(P)
   print(Q)
   print(R)
   print(S)

Output:

   51
   52
   [53, 54, 55, 56, 57, 58]
   59

Here 51 is being added to P, 52 is being added to Q but since then the rest is being added to R. And the last value of the iterable on the right is being added to the last variable S on the left.

List in Python

There are 6 types of built-in types in Python. They are – Numeric, Sequence, Mapping, Class, Instance, and Exception. The most basic data structure is Sequence. Each of these elements is assigned to a number called index or position. The first index is zero, then 1, and then increases in order.

Python again has 3 types of basic sequence types that are List, Tuple, and range/xrange Object. In this section, we will discuss the Python List.

We generally put the value in a variable. But if we need to assign a lot of values at once, then declaring a variable one by one is a lot of hassle and time-consuming.

So we can use the list method to make this work more easily,

Example:

   P = 3
   Q = 8
   R = 1
   S = 0
   T = 5
   print(f"This is from one by one variable -> {[P,Q,R,S,T]}")
 
   number = [3,8,1,0,5]
   print(f"This is from List -> {number}")

Output:

   This is from one by one variable -> [3, 8, 1, 0, 5]
   This is from List -> [3, 8, 1, 0, 5]

Each item placed on this list will be called an element of that list. We can access these elements like this,

Example:

   number = [3,8,1,0,5]
   var1 = number[0]
   var2 = number[1]
   var3 = number[2]
   var4 = number[3]
   var5 = number[4]
   print(var1, var2, var3, var4, var5)

Output:

  3 8 1 0 5

Here the first index started from zero. That’s why we put this number[0] in the var1 variable, and then increase it in order. As number[1],number[2],number[3],number[4].

We can keep the other on a list. Here one character will be an element on that list.

Example:

   we = ['e','n','a','b','l','e','g','e','e','k']
   print(we)
   print(we[5], we[6])
   print("The length of this list:",len(we))

Output:

   ['e', 'n', 'a', 'b', 'l', 'e', 'g', 'e', 'e', 'k']
   e g
   The length of this list: 10

The total number of how many elements on a list is the length of that list. Here len(we) is the length of the list.

Empty List

A blank list can be made like the following,

Example:

   first_list = []
   print(first_list)

Output:

   []

Element type

Different types of data or elements can be kept in a list in Python. For example, some numbers, some strings, or even one or more lists can be kept as an element in one list. Although it is usually a good practice to keep the same element on a list.

Example:

   number = 38
   numbers_list = [number, 10, 83]
   list_object = ["Numbers", 0, numbers_list, 4.56]
 
   print(list_object[0])
   print(list_object[1])
   print(list_object[2])
   print(list_object[2][2])
   print(list_object[3])

Output:

   Numbers
   0
   [38, 10, 83]
   83
   4.56

String as a List

A string type value behaves like a list in python, that is, each character in the string seems to be an element of an imaginary list.

Example:

   me = "EnableGeek"
   print(me[6])

Output:

   G

That is, me = “EnableGeek” And me = [“E”, “n”, “a”, “b”, “l”, “e”, “G”, “e”, “e”, “k”] is virtually the same. And so the value of me[6] is coming ‘G’.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article