In this series about Python, we will take a closer look at Data Types and Data Structures. We will unravel their concepts in a simple and understandable way, without any complex jargon. By the end of this article, you will have a solid understanding of how Data Types and Data Structures work in Python. Let's get started & learn how to organize and manipulate data with ease.
Data Types
Data types in Python are like different containers that hold specific types of information. Imagine a toolbox with compartments for different tools. Similarly, Python has different data types for storing and working with different kinds of data.
Let's take a look at some of the common data types in Python:
Numbers: They represent numerical values. It's like having a box dedicated to numbers. You can put whole numbers (integers), decimal numbers (floats), or even complex numbers in this box.
Strings: They are like containers for text. It's as if you have a box for storing words, sentences, or even entire stories. You enclose the text in quotes (either single or double) to create a string.
Lists: They are versatile containers, just like a bag that can hold various items. You can put different types of data, such as numbers, strings, or even other lists, into this bag.
Booleans: They are like switches with only two positions: on or off. It's similar to having a box with labels like "True" and "False". You can use these switches for decision-making or checking conditions.
Dictionaries: They are like special organizers, resembling a real-life dictionary. Instead of words and definitions, Python dictionaries store key-value pairs. You use a word (key) to quickly find its meaning (value).
These data types serve different purposes and allow you to work with a wide range of information in Python. Understanding data types helps you choose the right container for your data and perform operations accordingly.
In case, you haven't gone through my previous article I would suggest giving it a read to understand Data Types better - Python Basics
Data Structures
Data structures, as the name suggests, are mechanisms or techniques used to organize and store data in a computer's memory. They provide a means to manage and manipulate data efficiently, enabling effective storage, retrieval, and modification of information. Data structures define the layout and organization of data, as well as the operations that can be performed on that data.
Data structures can be implemented using different programming languages, including Python. In Python, there are built-in data structures like lists, tuples, sets, dictionaries, and strings, as well as the ability to create custom data structures using classes and objects. The choice of data structure depends on factors such as the type of data to be stored, the desired operations to be performed, and the efficiency requirements of the application.
Data structures can be broadly categorized into two main types:
1) Primitive DS
2) Non-Primitive DS
Primitive Data Structures:
Integer: Represents whole numbers, such as 1, 2, -3, etc.
Float: Represents decimal numbers, such as 3.14, -0.5, etc.
Boolean: Represents either true or false.
Strings: Sequences of characters used to represent text.
Non-primitive Data structures:
Non-primitive data structures in Python are more complex and advanced compared to primitive data types. They provide a way to organize and manipulate larger and more complex collections of data. Here are some common non-primitive data structures in Python:
Lists: Dynamic arrays that can grow or shrink in size and can store elements of different data types.
Tuples: Similar to lists, but immutable (unchangeable) once created.
Sets: Unordered collections of unique elements.
Dictionaries: Key-value pairs, where each value is associated with a unique key.
Arrays: Contiguous memory locations used to store a fixed-size sequence of elements of the same data type.
Stacks: Follows the Last-In-First-Out (LIFO) principle, where elements can be added or removed only from the top.
Queues: Follows the First-In-First-Out (FIFO) principle, where elements can be added at one end and removed from the other.
Linked Lists: A collection of nodes, where each node contains a value and a reference to the next node.
Trees: Hierarchical structures with a root node and child nodes that can further have their child nodes.
Graphs: Collections of nodes connected by edges, used to represent relationships between entities.
TASKS
Give the Difference between List, Tuple and Set. Do Handson and put screenshots as per your understanding.
Create a Dictionary and use Dictionary methods to print your favourite tool just by using the keys of the Dictionary.
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.[Hint: Use keys to built in functions for Lists]
Task-1: Give the Difference between List, Tuple and Set. Do Handson and put screenshots as per your understanding.
Property | List | Tuple | Set |
Mutability | Mutable | Immutable | Mutable |
Order | Ordered | Ordered | Unordered |
Duplicates | Allows | Allows | Eliminates |
Syntax | Square Brackets ([]) | Parentheses () | Curly Braces ({}) or set() |
Example |
|
|
|
Examples:
LISTS-
# Lists
fruits = ["apple", "banana", "orange"]
fruits.append("kiwi")
print(fruits)
Output:
In the above example, we have created a list of fruits and then we are trying to add a new fruit ''kiwi'' to the list by using append()
. By printing the fruits list we can see kiwi is added to the list which implies Lists are mutable.
TUPLE-
Let's create a tuple called "colors" with contents ("red", "green", "blue") and now if you attempt to use the append()
method on the colors
tuple it will result in an error (AttributeError: 'tuple' object has no attribute 'append') as shown below in first output
# Tuples
colors = ("red", "green", "blue")
# colors.append("yellow")
print(colors)
Output:
If you try to run the program without trying to append a new value, you will get the result as shown in above image. This implies tuples are immutable, meaning they cannot be modified after creation. You cannot add, remove, or modify elements.
SETS-
Sets are mutable and unordered collections of unique elements. They automatically eliminate duplicate values. You can add elements to a set using the add()
method. In the below example, we added the number 6 to the numbers
set, and when we added the number 1 again, it was automatically removed as duplicates are not allowed.
# Sets
numbers = {1, 2, 3, 4, 5}
numbers.add(6)
numbers.add(1) # Duplicates are automatically removed
print(numbers)
Output:
Task-2: Create a 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"
}
print("My favourite tool is ", fav_tools[4])
Output :
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.
Program:
cloud_providers = ["AWS", "GCP", "Azure"]
cloud_providers.append("Digital Ocean")
cloud_providers.sort()
print(cloud_providers)
append()
- Adds an element to the end of the list.
sort()
- Sorts the list in ascending order.
print()
- Displays the specified content or values on the standard output (usually the console). It allows you to output text, variables, or the result of expressions.
Output:
We have successfully completed all tasks of today's challenge and learnt about Data Types and Data structures in Python. I hope you found this article helpful. If you did, please give it a Like. As always, your feedback and suggestions are highly appreciated. Feel free to drop them in the comments section. Bye!!