Python Data Structure-A Pythonic way of storing your data

List/Tuple/Dictionary/Set

Prabhakar Pandey
6 min readSep 17, 2020
Python Data Structure- List, Tuple, Dictonary. Set

A Data Structure is a way of organizing the data in the system so that it can be used effectively. A Data Structure is a collection of Data Values, the relationship among them, and the function or operation that can be applied to the data.

Ex: We can store a list of items having the same data type using an array data structure.

Data Structure types:

Homogeneous:

When the type of the data is the same called Homogeneous Data Structure

o 1 dimensional >> array

o 2 dimensional

o Multidimensional

Heterogeneous:

When the type of the data is differently called Heterogeneous Data Structure

o 1 dimensional

o 2 dimensional >> table (The Table may have the different types of Data columns.)

o Multidimensional >> containers

Core Python’s Data Structure: Python provides only 1-Dimensional Heterogeneous Data Structure.

which is four types:

*Tuples

*List

*Dictionary

*Sets

Python Data Structure- List, Tuple, Dictonary, Set

Tuples

A tuple is a Python 1-D Heterogeneous Data Structure
tuple is created using round bracket () (parenthesis)

Ex- t1= (123,456,789) o/p: (123,456,789) type(t1)

o/p: Tuple
The output of the tuple also contained within the bracket
Keep in Mind:

x=2 ##Every time the no of the element is one when we assign the value, If the no of elements is increased then the object call become the data structure
type(x) o/p=int
x=2,3 ## No of elements are increased so it’s a tuple Data Structure since this obj require a data structure to store the values or element ##Homogeneous Data Structure
type(x) o/p=tuple
x=123,’abc’,345 ##Heterogeneous Data Structure, doesn’t care if it is Homogeneous or Heterogeneous so can be int, char, string
type(x) o/p= tuple

How to Create Tuple:

Tuple can be creating in Two ways-

#Method1- Not advised

t0=123,456,789

type(t0) o/p=tuple

#Method2- Advised

t1= (123,456,789)

type(t1) o/p=tuple

List

A List is a Python 1-D Heterogeneous Data Structure, List is created using square bracket []

Ex- l1=[123,456,789]

Oput: [123,456,789]

type(l1)

oput: List

The output of the List also contained within bracket

##Create a list

l1=[123,456,789]

type(l1) o/p=list

Why Python provides tuple and list data structure while the booth is looking same both are the 1d-heterogeneous data structure

t1=(123,456,678)

l1=[123,456,789]

sub-setting or Extracting Elements from List/Tuple: The method of subsetting or accessing the value from List or Tuple are the same

l2 = [1,5,7,9,15,23,78,100]

Extract 1st element

l2[0] o/p=1

Keep in Mind:

In python, the position number of the elements is called as the index.

The index starts from 0

Index number = Element Number — 1

# e.g. l2 = [1,5,7,9,15,23,78,100]

Extract the 3rd element

index number = 3–1

index number =2

l1[2] output: 7

Note: For extracting the element we use object name and index no (position no) in bracket [] ie. l2[0]

Extracting 1st to 6th element (1, 5, 7, 9, 15,23)

l2[0:5] # The upper bound is exclusive in python so the 6th element (23) will not consider

o/p= [1, 5, 7, 9, 15]

#for the 6 the element

l2[0:6]

o/p= [1, 5, 7, 9, 15, 23]

Extracting the value from 2nd index to all:

l2[2:]

o/p= [7, 9, 15, 23, 78, 100]

Extracting the value from the starting index to till 2nd index:(0 to 2nd index)
l2[:2] # Staring to 2nd index should be 1,5,7 but upper bound exclusively in python so the 2nd index(value 7) will not consider

o/p=[1, 5]

starting index to till 2nd index: (0 to 2nd index)

l2[:3]

o/p=[1, 5, 7]#Extract the value with stepl2[0:7:2]  # 0 to 7th index value with step 2 means here is upper bound exclusive (100 will not consider) and step with 2 value means 5,9,23 will not extracto/p= [1, 7, 15, 78]

Note: We create a tuple by use of () but we access the tuple by [] and we create & access the list by []

We can’t access tuple like t1(0) it gives error not callable

List vs Tuple

Tuples are immutable means Tuples cannot be edit, List is mutable means List can be edit

Note: The assignment operator (=) used to save the value

l2
[1, 5, 7, 9, 15, 23, 78, 100]
l2[1]*2 #1st index value multiplying by 3, We can edit the list (multiply by 3) and can save the value by assignment operator(=)

Save the value in List

l2[1]=l2[1]*3l2o/p=[1, 45, 7, 9, 15, 23, 78, 100]t2 #Tuple
(1, 5, 7, 9, 15, 23, 78, 100)
t2[1]*3 #We can multiply but cant save the value since Tuple is immutable

Save the value in Tuple
t2[1]=t2[1]*3 #1st index value multiplying by 3, We cant edit the Tuple since its immutable (multiply by 3) and cant save the value by assignment operator(=), Its give type error ‘ ‘tuple’ object does not support item assignment’

TypeError: 'tuple' object does not support item assignment

Note: We cant edit the Tuple Since Tuples are immutable, Once the Tuple always Tuple, We can do arithmetic operation on Tuple values but cant save.
We can edit the List Since List are mutable

Use Case: Why we have Tuple or List,
Store permanent values like DOB, Name we can use Tuple, Store temporary values like Age, A/C type we can use List.
Like OTP for mobile, no cant be edit and match with the server so we use Tuple for security purpose.

Dictionary

A Dictionary is a Python 1-D Heterogeneous Data Structure
Dictionary is created using square bracket {} with use of key & value pairs
Syntax- dict1=[‘key’:value,’key’:value,’key’:value,] #Key is like the index(0,1,2..) and Values can be any object list, tuple, dictionary

Ex: dict1 = {‘SName’: ‘Amit’, ‘SAge’: 30, ‘SCity’: ‘Blore’}

dict1

Oput: {‘SName’: ‘Amit’, ‘SAge’: 30, ‘SCity’: ‘Blore’}

type(dict1)

Oput: dict
The output of the List also contained within curly braces {}

Keep in Mind:

Note: In tuple & list we create an object we assign multiple elements to the object and we access the element by the index while Dictionary is different than list and tuple, In the dictionary, we use curly braces {} then we provide key and value.

Ex: school_database={‘Name’:[‘Amit’,’Rohit’,’Pankaj’],’Score’:[20,32,24],’Location’:[‘Delhi’,’Bangalore’,’Noida’]}

school_database
o/p= {'Name': ['Amit', 'Rohit', 'Pankaj'],
'Score': [20, 32, 24],
'Location': ['Delhi', 'Bangalore', 'Noida']}
##Dictionary attribute 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(dir(school_database))

Extracting keys

for i in school_database:  ##Getting only key
print(i)
o/p=
Name
Score
Location
for i in school_database: ##Getting only values, since dictanry have three list
print(school_database[i])
o/p=
['Amit', 'Rohit', 'Pankaj']
[20, 32, 24]
['Delhi', 'Bangalore', 'Noida']
Note: We can use values()& keys() function to extract same

Extract/Access the Dictionary Values:
We cant access the Dictionary values like list and tuple for ex:school_database[0] its give the Error: KeyError: 0 since these are not index theses are the Keys so we need to pass the Key (name,score,location..etc are keys),

for Ex: school_database[‘Name’]

oput-[‘Amit’, ‘Rohit’, ‘Pankaj’]

school_database[0] #Error:KeyError: 0 since dictionary doesn't have the index

school_database['Name']
school_database['Score']
school_database['Location']
o/p=
['Delhi', 'Bangalore', 'Noida']

Use Case: Dictionary is generally used to create the Table(Data Frame) Since the Table has row and column as in format.
First Create the dictionary then pass a dictionary to the data frame, Keys become the column name and rows become the row values.

#Use the Dictionary in Table/Data frame
import pandas as pd
pd.DataFrame(school_database)
o/p=
Name Score Location
Amit 20 Delhi
Rohit 32 Bangalore
Pankaj 24 Noida

Sets

A Sets are a Python 1-D Heterogeneous Data Structure, In Python Sets is a group of Distinct ordered elements.
Sets is created using round bracket curly braces {}

Ex- set1 = {1,2,1,1,2,4,5,4,4,8,7,9,3,1,9,6,5,9,9,7,1,4,2,1,5}set1
o/p=
{1, 2, 3, 4, 5, 6, 7, 8, 9}
type(set1)
o/p=
set

The output of set automatically in ordered with distinct values.
Use case of Set: Whenever we need to pic only distinct sorted values from a set of values then we use set.

set1 = {1,2,1,1,2,4,5,4,4,8,7,9,3,1,9,6,5,9,9,7,1,4,2,1,5}
set1 #Distinct sorted values
o/p=
{1, 2, 3, 4, 5, 6, 7, 8, 9}

Keep in Mind:

We should not assign the value in predefined keyword (list,set) like set={1,2,3,1}, The set is predefined keyword or function we should not overwrite it otherwise we will not able to use it to further.
For Ex: We have a list l1 and we want to convert this list into a set but suppose we have already overwritten the predefined set variable(set={1,2,3}) in our above code then we cant use(convert) it until we release that set keyword using (del set) or we get the error ‘set’ object is not callable’.

delete a predefined object
del set

Use case: Convert list into set, Suppose we have list of salaries we want to show the distinct salary out of the list to check threshold of salary

l1 =[1, 2, 3, 2, 1]
s1 = set(l1) #Convert list into set by set() function
s1
{1, 2, 3}

If you find it useful, do clap and share it among your enthusiastic peers

More to come! Stay tuned, and thanks for reading :)

Happy Learning !!

--

--