Day14 of #90DaysOfDevOps Challenge

Data structure in Python

Day14 of #90DaysOfDevOps Challenge

In the Last Article, we read about Data types. Everything is an object in Python. The data type is a class and a variable is an object of that class.

Now we will see, what data structure is in Python.

⚡ Data structure in Python

A data structure in Python is a way to store and organize data efficiently. The data structure in Python is categorized as Primitive and Non-primitive, based on its fundamental characteristics and usage.

🔹Primitive Data Type:

These are the basic and fundamental data types provided by the programming language which are immutable, meaning their values cannot be changed once assigned.

Following are the different types of Data Types -

  • Integer (int): Represents whole numbers, such as 1, 2, -5, etc.

  • Float (float): Represents floating-point numbers with decimal values, such as 3.14, -0.5, etc.

  • Boolean (bool): Represents the truth values True or False.

  • Character (str): Represents individual characters or strings of characters, such as 'a', 'hello', etc.

  • None (NoneType): Represents the absence of a value or a null value.

To check the class of any variable value, we can use the below command-

print(type(var))

No alt text provided for this image

🔹Non-Primitive Data Structure

Non-primitive data structures are complex data structures composed of one or more primitive data types or other non-primitive data structures. They are also called composite data structures or abstract data types. They can be modified, expanded, and manipulated to suit specific programming needs.

Following are the examples of non-primitive data structures:

  • Lists: Ordered collections of elements of different data types (str, int, float, bool). Lists are mutable and allow modifications like adding, removing, or modifying elements.

Lists are denoted by square brackets ([]).

  • Tuples: Similar to lists, but tuples are immutable, meaning their elements cannot be changed once defined.

Tuples are denoted by parentheses (()).

  • Sets: Unordered collections of unique elements. Sets do not allow duplicates and provide operations like union, intersection, and difference.

Sets are denoted by curly braces ({}) or the set() function.

  • Dictionaries: Key-value pairs where each key is unique and associated with a value. Dictionaries provide efficient lookup and retrieval based on keys.

They are denoted by curly braces ({}). Keys within dictionaries must be unique.

  • Arrays: Arrays are used to store a collection of elements of the same type in contiguous memory locations.

Arrays in Python are provided by the array module.


⚡Tasks

🔹Task 1 - Give the Difference between List, Tuple, and Set. Do Handson and put screenshots as per your understanding.

No alt text provided for this image

No alt text provided for this image

In the above screenshot, we used timeit library which gives us the execution time of an operation. And we can see that Tuple is faster and more efficient.=>

List:

List_of_names = [ ] -> Empty list

Important operations-

  1. Append - To add values to the list.

Syntax:

List1.append(value)

List_of_names.append("Aish")

List_of_names.append("Priya")

No alt text provided for this image

2. Clear - To empty the list.

Syntax:

List1.clear()

No alt text provided for this image

3. Count - To count the occurrences of any value.

List_of_num = [1, 1, 2, 3, 4, 2, 2, 1]

Print(List_of_num.count(1))

No alt text provided for this image

No alt text provided for this image

4. Extend - To combine 2 lists.

List_of_names.extend(list_of_nums)

No alt text provided for this image

5. Len - We can get the length of the list meaning the total number of values in a list.

Print(len(list_of_names))

No alt text provided for this image

6. Dir - To know what are all the operations can be done for that list.

Print(dir(List_of_names))

7. Index in the list - Position of the value in the list, starts with 0.

Print(List_of_names[0])

8. Slicing - We can iterate the list and get only a part of the list in the output.

Print(List_of_names[0:3])

  • It will slice the list with values starting from the 0th to the 2nd position.

Print(List_of_names[1:4])

  • It will slice the list with values starting from the 1st to the 3rd position.

9. Concatenate - Combine two lists, so now list one is appended with list 2 and the number of values in the list1 is list1+list2.

List1.extend(list2)

Print(list1)

No alt text provided for this image

Tuple:

  • It's a sequence of values.

T1 = 10

T2=("2") -> not a tuple

T2=("2",) -> It is a Tuple as it is a sequence now.

No alt text provided for this image

  • We can not change the value of a tuple - Immutable

T2 = (1,2,3)

T2[0].append(2) -> cannot be done

No alt text provided for this image

T2=([1,2,3], 4, 6)

T2[0].append(4) -> will change the value since the 0th element is a list that is mutable.

No alt text provided for this image

  • Packed and unpacked tuples-

T2 = (10,20,30) -> Pecked tuple

Print(T2) -> will show packed value -> (10,20,30)

a,b,c = (10,20,30) -> unpacked tuple

Print(a,b,c) -> shows unpacked value -> 10 20 30

No alt text provided for this image

Set:

  • Unordered collection.

Input - banana, mango grapes.

Output - grapes, banana, mango.

No alt text provided for this image

  • Only holds unique values.

Here banana is added twice in the set but the set only allows a single occurrence.

No alt text provided for this image

Important operations-

  1. Add

No alt text provided for this image

2. Remove

No alt text provided for this image

3. Union

Combines two sets.

No alt text provided for this image

4. Intersection

Common values in both sets.

set1.intersection(set2)

No alt text provided for this image

5. Difference

set1.difference(set2)

Common values in set1 and set2 will be removed from set1.

A-B = C

No alt text provided for this image

6. Subset/superset

Check if set2 is a subset of set1 or set1 is a superset of set2.

Subset - > All values of set2 is in set1 then set2 is subset of set1

Superset -> set1 is a superset of set2 in the above ex.

No alt text provided for this image

🔹Task 2 - Create the below Dictionary and use Dictionary methods to print your favorite tool just by using the keys of the Dictionary.

fav_tools = 
{ 
  1:"Linux", 
  2:"Git", 
  3:"Docker", 
  4:"Kubernetes", 
  5:"Terraform", 
  6:"Ansible", 
  7:"Chef"
}

To print the values of all the keys in the above dictionary, I used for loop and iterate the keys to get all the values.

for i in fav_tools:

print(fav_tools[i])

No alt text provided for this image

Or use the get method -

No alt text provided for this image

🔹Task 3 - Create a List of cloud service providers eg.

cloud_providers = ["AWS","GCP","Azure"]

Write a program to add Digital Ocean to the list of cloud_providers and sort the list in alphabetical order.

No alt text provided for this image

⚡Conclusion:

In this Article, we learned about data structures in Python and did exercises on different operations in List, Tuple, set, and dictionary. We also saw the difference between List, Tuple, and Set.

Hope this was knowledgeable. 😁


Thank you for Reading!📘