Data Structure in Python || List || Tuple || Set || Dictionary

Firstly we need to understand the data structure and then we will know how it is implemented in python. We will start from very basics and will cover the complete data structure of Python.

Data Structure introduction:

Data structure is a vast field of computer science in which arrangement of data is defined. It perform many task to provide efficient way for manipulation, operation, modification and access of data.

The main part cover by the data structure is:
1. Data Management: Management way of the data in storage device. It is responsible for easy data storage and retrieval, Provide security of multiple users etc.

2. Data Organisation: Classification and arrangement data to make it easy to use.
3. Data storage: Storage of data in volatile, non-volatile and semi-volatile disk in a efficient manner.

Python also provide some type of data structure to make its interpretation easy.
Note: Python is officially interpreted language but many other system of python IDE provide compilation feature.

In easy language data structure is also known as data-type in computer science with upper level abstraction view. Obvious data structure is a separate field which is responsible to arrange all type of data. But in programming sense we can understand, the structure of data by their type. data-type is reflaction of data structure.

For example:
a=5

Here “a” is a variable and contain the assigned integer value 5. It means we are defining a variable of integer type which will occupy the memory in storage disk with a particular physical and logical address. Further, on calling of variable, it will refer to assigned address and fetch the stored value. Name of variable is abstraction of address of particular memory address. Apart form this side we will focus on main part of this tutorial i.e, data-type.

In python you can directly assign variable with any data-type. Their is not any requirement of initialization. In general term this feature is known as dynamic typing.
Let me clear one thing also that, in python there is not any types of variable. The label of value which is associated that variable become the data-type of that variable.

For example:
text=”Aisangam”
Here we have been directly initiated a variable ”text”. Python interpreter will automatically understand that “text” is a sting type variable.

Now we will understand each data structure with example as shown in tree structure image.

Data Structure in Python

Data Structure in Python

Primitive data-type:

The most basic type of data is known as primitive data-type. Such type of data-type cant be separated further. For example numbers and string.

Ex:
a= 5
b=”Aisangam”

Boolean:

Boolean is a very common data-type used in mostly all type of computer programming language. This data-type contain only two values, True or False (1 or 0).This data-type is used in conditional operator to check that condition is True or False.

Lets understand this with the help of example.

barrier=True
if barrier==True:
print(“Welcome to Aisangam”)
else:
print(“Condition is False”)

In this code snippet barrier is a variable containing boolean value. Further using “if” statement it is checked that condition is true or false. Because here condition is True so it will print “Welcome to Aisangam”.

You can also perform mathematical operation on boolean data-type. It acts like other number data-type.

a= True+5
Print (a)
Output: 6

a= False+5
Print (a)
Output: 5

here True work as 1 and false work as 0.

Strings:

String is also a most common primitive data-type used in mostly all programming languages. In python any number, character, symbol enclosed by single (‘’)or double (“”) quote is interpreted as string data-type. String is a immutable (fixed) data-type. Immutable data-type means the variable is allocated memory only once at the time of its declaration. Further it can be only re-use in through-out the program.
For Example:

text= “This is Aisangam Tutorial”
Print (text)
Output: This is Aisangam Tutorial

Further, if you have to print text in multiple line then you can enclose text with three double quote.

For example:

text=”””This is Aisangam tutorial.
Aisangam welcomes you.”””
print (text)

output:
This is Aisangam tutorial.
Aisangam welcomes you.

String works like list in the way of slicing. Slicing means you can get only certain part of string from their index value.

text= “This is Aisangam Tutorial”
Print (text[8:])

output: Aisangam Tutorial

Explanation:
text[8:] this type of text separation is known as slicing. it is defined like
[start_Index:end_Index] type of indexing. By default it start with 0 index and end with last index.

In depth when you will work with different language-type or format then there will be great problem of encoding. In python there is some key confliction which have to know. It will help you to solve many challenges in future.

In python 2.7

text=”Aisangam”
print(text, type(text))

text=u”Aisangam”
print(text, type(text))

Output:
Aisangam, <type ‘str’>
Aisangam, <type ‘unicode’>

In python 3.5

text=”Aisangam”
print(text, type(text))

text=u”Aisangam”
print(text, type(text))

Output:
Aisangam, <type ‘str’>
Aisangam, <type ‘str’>

From this code part we got that python2.7 support both encoding(Non-unicode(ASCII) and unicode) by default.But python3 support unicode(UTF-8) by default.

Numbers:

Number is most usable data-type in all languages. The supported data-type inside numbers is
1. int
2. float
3. complex

Int: It contain all type of integer value and the maximum size of this data-type is unlimited. You can assign value as max as possible according to the memory size.

Ex:
a=5
print (a, type(a))

Output:
5, <class ‘int’>

Float:
It contain decimal values. After decimal it can contain 15 values.

Ex:
a=5.004
print (a, type(a))

Output:
5.004, <class ‘float’>

Complex:
As mathematics you can define complex value which is also known as imaginary value.

Ex:
a= 2+7j
print (a,type(a))
output:
(2+7j),<class ‘complex’>

Bytes:

Bytes is a machine understandable language. Human cant read it. So when machine need to communicate with machine then often we use this type of data-type. Networking, socket programming is the best field of programming where this data-type is used frequently. This data-type make system fast because there is not need of changing in encoding unlike another data-type. Such type of variable can store a sequence of bytes ranging from 0 to 255. It is a immutable data-type.

Ex:
ins = bytes(16)
print(ins,type(ins))

Output:
b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′ <class ‘bytes’>

Non-Primitive data-type:

Collection of primitive type data is known as non-primitive data-type. This type of data can be further separated in primitive data-type. For Example List and Dictionary.

Ex:
a= [1,2,”Aisangam”]
b={“name”:”Aisangam”,”Location”:”India”}

List:

List is a array like data-type in which we can store data in a sequential order. Unlike array it can store heterogeneous data-type element.

Ex:
li=[‘aisangam’,1,2+5j,8.08]
print (li,type(li))

Output:
[‘aisangam’, 1, (2+5j), 8.08] <class ‘list’>

Slicing in list:
As we have already discussed in string, List support slicing.

Ex:
print(li[1:2])

output:
[1]

In list you can put any data-type. List is mutable. You can alter list with the help of its index number.

Ex:
li[2]=5
print (li,type(li))

output:
[‘aisangam’, 1, 5, 8.08] <class ‘list’>

Tuple:

It is same like list but have some key differences. It cant be modified as list. Tuple is immutable but list is mutable.
List notation is [] but tuple notation is ().

Some benefits of tuple:
Light-weighted
Work as constant
Can be useful to make key for dictionary
Single container etc.

Ex:

tuple=(‘aisangam’,1,2+5j,8.08)
print (tuple,type(tuple))

Output:
(‘aisangam’, 1, (2+5j), 8.08) <class ‘tuple’>

Dict:

Dictionary is a very efficient data structure to store a large data. Dictionary is Un-ordered collection of data in which data is stored in key-pair wise. This is highly optimised for retrieval of particular data from a large data collection.

Ex:
di={
“Key”:”value”,
“name”:”ABC”,
“Company”:”AISangam”
}

With the help of key data can be directly access.

Ex:
print(di[“Company”])

output:
AISangam

In this non-primitive any type of data can be stored as value of any key. At dynamic time you can also change the value as it support mutable behavior.

Ex:
di[“Key”]=0
print(di)

output:
{‘Company’: ‘AISangam’, ‘name’: ‘ABC’, ‘Key’: 0}

There are some important functions used in dictionary.
Keys():

print (di.keys())

Output: [‘Company’, ‘name’, ‘Key’]

Values():

print (di.values())
Output: [‘AISangam’, ‘ABC’, 0]

items():

print (di.items())
Output: [(‘Company’, ‘AISangam’), (‘name’, ‘ABC’), (‘Key’, 0)]

Add new Key to dict:

di[“Location”]=”India”
print(di)

output:
{‘Company’: ‘AISangam’, ‘name’: ‘ABC’, ‘Key’: 0, ‘Location’: ‘India’}

Update dict:

di.update({“TimeZone”:”IST”})
print(di)

output:
{‘TimeZone’: ‘IST’, ‘Company’: ‘AISangam’, ‘name’: ‘ABC’, ‘Key’: 0, ‘Location’: ‘India’}

Delete particlar key from dict:

del di[“Key”]
print(di)

output:
{‘TimeZone’: ‘IST’, ‘Company’: ‘AISangam’, ‘name’: ‘ABC’, ‘Location’: ‘India’}

Sets:

Set is an un-ordered and immutable data structure in python. This data-type can perform mathematical operation like set theory. The common mathematical operation of Set is Union, Intersection, difference etc.

Ex:
set={“Aisangam”, “India”, “IST”}
print (set)

Output:
set([‘India’, ‘Aisangam’, ‘IST’])

In set all the element remain unique. So for removal duplicate entry in list you can take the help of set.

Ex:
li=[“Aisangam”,”India”,”IST”,”Aisangam”,”IST”]
print (li)

li_set=set(li)
print(li_set)

Output:
set([‘India’, ‘Aisangam’, ‘IST’])

Frozen set:
Frozen set is a traditional type of set. After creating a frozen set it cant be modified. This is immutable data structure.

Ex:
simple_set = {“Ai”, “Sangam”}
simple_set.add(“India”)
print(“Simple Set”,simple_set)
frozen_set = frozenset([“Ai”, “Sangam”, “India”])
print(“Frozen Set“,frozen_set)
sample_set.add(“IST”)
print(“Updated Frozen Set”frozen_set)
frozenset([‘Ai’, ‘Sangam’, ‘India’])

Output:
Simple Set,set([‘Ai’, ‘Sangam’, ‘India’])
Frozen Set,frozenset([‘Ai’, ‘Sangam’, ‘India’])
Updated Frozen Set,frozenset([‘Ai’, ‘Sangam’, ‘India’])

Conclusion:

In complete tutorial we studied about complete data structure in python.

14 thoughts on “Data Structure in Python || List || Tuple || Set || Dictionary”

  1. Aditya Kumar says:

    First of all it is my pleasure to write to you as I had seen all of your you tube videos as well has read all your blogs. You write effectively with proper documentation and quality. So please keep on doing this work in future also. Such articles are very useful to the common public and especially those who are interested in learning python.

    I have a common question: what is difference between print(‘this is \n a book’) and print(r’this is \n a book’)

    With regards
    Aditya Kumar

    1. AISangam says:

      Hello Aditya Kumar. It is pleasure to revert back to you. You spoke a lot of things and donot worry we will keep on writing the content. Coming back to your question. Let us see what would be the output when we execute the statement

      Output is as below

      As you can see that when the new line comes, the succeeding content will come in the next line.

      Now let us run the next code.

      Output is as below

      So in this the \n is printed as it is. I hope you understand the difference while performing the live example.

      1. Aditya Kumar says:

        Again a question arise in the mind. This is related to regular expression. I hope asking the question on Regex in the Data Structure is not so appropriate but i hope you would answer me here.

        My question is what is the relation between re.compile and re.match

        1. AISangam says:

          No problem, you may ask any question anywhere. Please see the explanation from code as below

          In simple words 1+2===>3

  2. Ali says:

    Hello ai sangam. I want to know how to use argparse.

    If you can provide an example it would be great.

    1. AISangam says:

      Thanks ali
      Please see the below example where I have concatenated two integers and found the square of them using argparse. Please have a look at the code

      Please type in the terminal python arg_max.py 1 1
      Output is
      121 as 1 1 are concatenated and becomes 11 and square of 11 is 121

  3. vansh says:

    Can you show an example where one can use lambda, list and map together.

    1. AISangam says:

      Thanks for such question.
      Please see the below code

      Output of the code

      1. vansh says:

        Can you show me the use case of list.

        If so please show it.

        1. AISangam says:

          This is the simple program which showcase the use of list where vowels in the entered string is counted.

  4. Karam says:

    I need to know how to convert the dictionary into list. Can you show me the easiest way to do so.

    1. AISangam says:

      Hello karam. I have provided two of the solutions on Quora. Please read comments for Al Sangam there. Here is the link https://www.quora.com/How-do-I-convert-a-dictionary-to-a-list-in-Python

      If you like to get simple solution, yes we can implement the same using the list comprehension. Please do see here

  5. Abhi says:

    Some times, I got struck in pop, remove and delete functions with list in python. Can you help me out,please.

    With regards
    Abhi

Leave a Reply

Your email address will not be published.