DEV Community

Cover image for Data Structures
Velda Kiara
Velda Kiara

Posted on • Edited on

Data Structures

A structure is an arrangement and organization of related elements in a system.
Data is translated information for processing.

A data structure is a fundamental way of organizing data for efficient access dependent on the situation.

Types Of Data Structures

Lists

A list is an ordered collection of data which can store elements of the same type and different type.


# how to create a list, using square brackets
list1 = [ ] #empty list
list2 =[1,2,3,4,5]
list3 =[1, 'e', 'g', 6.5, 8, 'i']
print(list2,list3)
#output [1, 2, 3, 4, 5] [1, 'e', 'g', 6.5, 8, 'i']
Enter fullscreen mode Exit fullscreen mode

List elements are accessed by the assigned index. The index starts from '0' and ends at 'N - 1', where N is the total number of elements.

print(list3[2]) #goes to item at index 2 in list 3
#g
Enter fullscreen mode Exit fullscreen mode

Slicing Lists

To slice a list you use the : operator. To slice the list the start index is included while the last index is excluded.

# List slicing, syntax list[ Initial : End : IndexJump ]
my_list = ['d','a','t','a','s','t','r','u','c','t','u','r','e','s']

# elements from index 2 to index 5
print(my_list[2:5])#last item excluded
print(my_list[2:6])#last item included

# elements from index 4 to end
print(my_list[4:])

# elements beginning to end
print(my_list[:])

"""
output
['t', 'a', 's']
['t', 'a', 's', 't']
['s', 't', 'r', 'u', 'c', 't', 'u', 'r', 'e', 's']
['d', 'a', 't', 'a', 's', 't', 'r', 'u', 'c', 't', 'u', 'r', 'e', 's']
"""
Enter fullscreen mode Exit fullscreen mode

Elements of a list can be changed, hence the term lists are mutable.
To change an item we can use the assignment operator =.

nums1 = [2, 4, 6, 8]

# modifying the 1st item    
nums1[0] = 1            

print(nums1)

# change 2nd to 4th items
nums1[1:4] = [3, 5, 7]  

print(nums1)   

# output
# [1, 4, 6, 8]
# [1, 3, 5, 7]   
Enter fullscreen mode Exit fullscreen mode

To add a value to a list we use the append() method, for multiple values we use the extend() method. Concatenation of lists is when two or more lists are combined together. To concatenate use the + operator

# Appending and Extending lists in Python
nums = [1, 4, 5]

nums.append(8)

print(nums)

nums.extend([10, 11, 13])

print(nums)

nums.extend([20,15,14,16,18])

print(nums)

# output
# [1, 4, 5, 8]
# [1, 4, 5, 8, 10, 11, 13]
# [1, 4, 5, 8, 10, 11, 13, 20, 15, 14, 16, 18]
Enter fullscreen mode Exit fullscreen mode

List comprehensions

This is a simple way to create a new list from a existing one.
Syntax is [expression for item in list].

#an example of list comprehension and if statement
nums2 = [ x for x in range(10) if x % 2 == 0]
print(nums2)
#[0, 2, 4, 6, 8]

Enter fullscreen mode Exit fullscreen mode

To iterate through lists we use the for statement, and not in statements. Other list properties can be found here

Dictionaries

Dictionaries are collections with key:value pairs.
To create a dictionary use the {}, curly braces. To access elements we use the keys inside square brackets[], or the get() method.

#empty dict
shuri = {}

# get vs [] for retrieving elements
shuri = {'title': 'ray', 'number': 16}

# Output: ray
print(shuri['title'])

# Output: 16
print(shuri.get('number'))
Enter fullscreen mode Exit fullscreen mode

To add or change items in a dictionary use an assignment operator =. If the key exists, the value is updated, whereas if the key is not available, both the key and value are added.

shuri = {'title': 'ray', 'number': 16}
#adding a value 
shuri['color'] = 'purple'

print(shuri)
#update the value
shuri['title'] = 'sheldon'

print(shuri)

# output
# {'title': 'ray', 'number': 16, 'color': 'purple'}
# {'title': 'sheldon', 'number': 16, 'color': 'purple'}
Enter fullscreen mode Exit fullscreen mode

pop() method is used to remove an item from the dictionary using the key provided. popitem() method removes and returns the key:value pair. To remove all items we use clear() method and to remove the whole dictionary we use the del keyword.

shuri = {'title': 'ray', 'number': 16, 'street':'kes', 'pages':123}
#adding a value 
shuri['color'] = 'purple'

print(shuri)
#update the value
shuri['title'] = 'sheldon'

print(shuri.pop('street'))

print(shuri)

print(shuri.popitem())

print(shuri)

#clear all the items
print(shuri.clear())

# delete the dictionary itself
del shuri

# output
# {'title': 'ray', 'number': 16, 'street': 'kes', 'pages': 123, 'color': 'purple'}
# kes
# {'title': 'sheldon', 'number': 16, 'pages': 123, 'color': 'purple'}
# ('color', 'purple')
# {'title': 'sheldon', 'number': 16, 'pages': 123}
# None
Enter fullscreen mode Exit fullscreen mode

Sets

Sets are created by either using the set() function or {} with items separated by commas. To add an item on a set use the add() method, for multiple items use update() method.
Sets do not store duplicates.

Items can be removed by using discard() and remove().
The main difference between discard and remove is that remove raises an error if the element is not in the set while discard leaves the set the same.

#create a set
shuri = set()
#add value to the set
shuri.add(4)
print(shuri)
#update values to the set
shuri.update([5,5,6], [7,11,12])
print (shuri)
shuri.discard(7)
shuri.remove(4)
print(shuri)

#other way to create a set
sam = {1,5,6}
print(sam)

# output
# {4}
# {4, 5, 6, 7, 11, 12}
# {5, 6, 11, 12}
Enter fullscreen mode Exit fullscreen mode

Set Operations

Union is merging two sets to one using the | operator.
Intersection is the common items in the sets. Can be done in two methods using the intersection() function or & operator.
Difference of the set is a set of elements in the first set but not in the second set or vice versa. We use the - operator. This can also be achieved using the difference() method.
Symmetric difference is set of elements in the first and second set but not in both. We use the ^ operator or the symmetric_difference() method.

#create a set
shuri = set()
#add value to the set
shuri.add(4)
print(shuri)
#update values to the set
shuri.update([5,5,6], [7,11,12])
print (shuri)
shuri.discard(7)
shuri.remove(4)
print(shuri)

#other way to create a set
sam = {1,5,6}
print(sam)

#union
print(sam|shuri)

#intersection
print(sam & shuri)

print(sam.intersection(shuri))

#difference
print(sam-shuri)
print(shuri.difference(sam))

#symmetric difference
print(sam^shuri)
print(shuri.symmetric_difference(sam))
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope you learned the different data structures, how to create and manipulate them.

Read more from these resources

Programiz
DSA, Geeks for Geeks
List comprehensions
Lambda functions
List slicing
Dictionaries
Set

Top comments (0)