Data Structures in Python

In python their are four types of basic data structures

  • Tuple

  • List

  • Dictionary

  • Set

Tuple

Tuple is an ordered collection of elements enclosed within brackets. Tuples are immutable.

tuple1 = (1, 1.25, 4, 8, 6)
Print(tuple1)
Output: (1,1.25,4)


type(tuple1)
Output: tuple


In: tuple1[0]
Output: 1

In: tuple1[1:2]
Output: 1.25, 4

In: tuple1[-1]
Output: 6

//Repeating tuple
In: tuple1 * 3
Output: 1, 1.25, 4, 8, 6, 1, 1.25, 4, 8, 6, 1, 1.25, 4, 8, 6

//Concatenate Tuple
tuple2 = (a,b,c)
print(tuple1 * tuple2)
Output: (1,1.25,4,a,b,c)

List

List is an ordered collection of elements enclosed within []. Lists are mutable.

li = [1,2,3]
In: print(li)
Output: [1,2,3]

In: print(li[0])
Output: 1

In: print(li[0:2])
Output: 1,2

In: li[0] = 25
In: print(li)
Output: [25,1,2,3]

In: li.append(50)
In: Print(li)
Output: [25,1,2,3,50]

In: li.pop()
In: Print(li)
Output: [25,1,2,3]

// Reverse elements of list
In: print(li.reverse()) 
Output: [3,2,1,25]

// Sort List
In: print(li.sort())
Output: [1,2,3,25]

// Insert Element at specific index
In: print(li.insert(1,"Hi"))
Output: [1,Hi,2,3,25]


Dictionary

Dictionary is an unordered collection of key-values pairs enclosed with {}. Dictionary is mutable.

d1 = {'Apple':10, Orange:20}

// Get type of
In: print(type(d1))
Output: dictionary 

// Get dictionary keys
In: print(d1.keys())
Output: dict_keys([Apple, Orange])

// Get dictionary values
In: print(d1.values())
Output: dict_values([10, 20])

// Adding a new element
d1["Mango"] = 90
In: print(d1)
Output: {'Apple':10, Orange:20, Mango:90}


// Changing an existing element
d1["Apple"] = 40
In: print(d1)
Output: {'Apple':40, Orange:20, Mango:90}

// How to update one dictionary element to another dictionary 
d2= {banana: 60, Grapes: 80 }
In: print(d1.update(d2))
Output: {'Apple':40, Orange:20, Mango:90, banana: 60, Grapes: 80}



Set

Set is an unordered and unindexed collection of elements enclosed with {}. Duplicates are not allowed in SET

s1 = {1,2,3}

// Print set
In: print(s1)
Output: {1,2,3}

// Add value in the set
In: print(s1.add(4))
Output: {1,2,3,4}

// Remove value in the set
In: print(s1.remove(3))
Output: {1,2,4}

// Union of two sets
s1 = {1,2,3}
s2 = {4,5,6}
s1.union(s2)
Output: {1,2,3,4,5,6}


// Intersection of two sets
s1 = {1,2,3}
s2 = {2,3,6}
s1.intersection(s2)
Output: {2,3}

Leave a Comment

Your email address will not be published. Required fields are marked *