Day 14:Python Data Types and Data Structures for DevOps
Table of contents
Data Types
- As we learned in the previous blog, data types are used to classify and categorize different types of data values that can be used in a program.
Since everything is an object in Python programming, data types are actually classes and variables are instances (objects) of these classes.
Python has the following data types built-in by default: Numeric(Integer, complex, float), Sequential(string,lists, tuples), Boolean, Set, Dictionaries, etc
To check what is the data type of the variable used, we can simply write:
datatype=1000
print(type(datatype))
Number
Data Type
Description
example
int
Integer type (whole number, no decimal)
1, 10, 100
float
Floating point type (one or more decimals)
13.6
complex
complex
6j
strings: A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Strings are immutable, which means that once a string is created, it cannot be modified.
- eg='d', "Dwarika", """he is learning DevOps"
There are many methods available for strings in Python. Here are some commonly used methods:
len()
: Returns the length of the string.lower()
: Converts all uppercase characters to lowercase.upper()
: Converts all lowercase characters to uppercase.strip()
: Removes any leading or trailing whitespace characters.split()
: Splits the string into a list of substrings using a delimiter character. By default, the delimiter is a whitespace character.join()
: Joins a list of strings into a single string using a specified delimiter character.replace()
: Replaces a specified substring with another substring.startswith()
: Returns True if the string starts with the specified prefix.endswith()
: Returns True if the string ends with the specified suffix.find()
: Searches the string for a specified substring and returns the index of the first occurrence. If the substring is not found, it returns -1.count()
: Returns the number of occurrences of a specified substring in the string.
example
my_string = "Dwarika jha"
print(len(my_string))
print(my_string.lower())
print(my_string.upper())
print(my_string.strip())
print(my_string.split(","))
print("-".join(my_string))
String slicing is a way to extract a part of a string in Python by specifying the start and end indices of the substring you want to extract. The syntax for string slicing is as follows:
string[start:end:step]
where string
is the string you want to slice, start
is the index where the slice starts (inclusive), end
is the index where the slice ends (exclusive), and step
is the stride or the number of characters to skip between each character of the slice (default is 1).
my_string = "Dwarika jha"
print(my_string[0:4])
Tuples: A tuple is a collection of ordered, immutable elements enclosed in parentheses.
You can also create a tuple using the built-in
tuple()
function, like thisTuples support indexing and slicing, just like strings
mytuple=(10, 1.5, "dwarika", "etc") print(mytuple[0]) print(mytuple[:3])
In Python, you can concatenate two or more tuples using the
+
operator. When you concatenate tuples, you create a new tuple that contains all the elements of the original tuples in the order they were concatenated. Here's an example:tuple1=(10, 1.5, "dwarika", "etc") tuple2=("devops","jenkis", "aws") tuple3=tuple1+tuple2 print(tuple3)
Lists: A list is a collection of ordered, mutable elements enclosed in square brackets. Each element in the list can be of any data type such as integer, string, float, or even another list. It also defines by using the list() method.
dwarika=["aws","jenkins","docker","ansible"]
Accessing elements in a list:
dwarika=["aws","jenkins","docker","ansible"] print(dwarika[0]) print(dwarika[1:3])#use for list slicing
There are many built-in methods that you can use to manipulate lists. Here are some of the most commonly used list methods:
append()
- Adds an element to the end of the listextend()
- Adds multiple elements to the end of the listinsert()
- Inserts an element at a specific position in the listremove()
- Removes the first occurrence of an element from the listpop()
- Removes and returns the last element of the listindex()
- Returns the index of the first occurrence of an element in the listcount()
- Returns the number of times an element appears in the listsort()
- Sorts the list in ascending order
dwarika=["aws","jenkins","docker","ansible"]
dwarika.append("maven") #append
print(dwarika)
dwarika.insert(0,"linux") #insert
print(dwarika)
devops=["tws","student"]
dwarika.extend(devops) #extend
print(dwarika)
Iterating over a list
dwarika=["aws","jenkins","docker","ansible"]
for i in dwarika:
print(i)
Sets: A set is an unordered collection of unique elements. They are similar to lists and tuples, but they cannot have duplicate elements, and their order is not guaranteed. Sets are defined using curly braces
{}
or using theset()
function.dwarika={"aws","aws","aws","jenkins","docker","ansible"} print(dwarika)
Sets have many built-in methods that you can use to manipulate them.
add()
- Adds an element to the setupdate()
- Adds multiple elements to the setremove()
- Removes an element from the setdiscard()
- Removes an element from the set if it is a member. If the element is not a member, it does not raise an error.pop()
- Removes and returns an arbitrary element from the setclear()
- Removes all elements from the setunion()
- Returns the union of two sets (i.e., all the elements that are in either set)intersection()
- Returns the intersection of two sets (i.e., all the elements that are in both sets)difference()
- Returns the difference between two sets (i.e., all the elements that are in set1 but not in set2)dwarika={"aws","aws","aws","jenkins","docker","ansible"} dwarika.add("linux") #add print(dwarika) dwarika.remove("aws") #remove print(dwarika) dwarika.clear() #clear print(dwarika)
Dictionaries: A dictionary is an unordered collection of key-value pairs, where each key is unique and associated with a value. Dictionaries are defined using curly braces
{}
or using thedict()
function.dwarika={1:"aws",2:"gcp",3:"azure"} print(dwarika)
Dictionaries have many built-in methods that you can use to manipulate them.
get()
- Returns the value associated with a key. If the key is not found, it returns a default value (None by default).keys()
- Returns a list of all the keys in the dictionaryvalues()
- Returns a list of all the values in the dictionaryitems()
- Returns a list of all the key-value pairs in the dictionary as tuplespop()
- Removes and returns the value associated with a keyupdate()
- Adds or updates key-value pairs in the dictionaryclear()
- Removes all key-value pairs from the dictionarydwarika={1:"aws",2:"gcp",3:"azure"} print(dwarika.get(2)) print(dwarika.keys()) print(dwarika.values()) print(dwarika.items())
Data Structures
A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently, Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages.
Primitive Data Structures:
Primitive or basic data structures. They are the building blocks for data manipulation and contain pure, simple values of data. Python has four primitive variable types:
Integers
Float
Strings
Boolean
Non-Primitive Data Structures
Arrays
Lists
Tuples
Dictionary
Sets
Tasks
Give the Difference between List, Tuple, and Set.
List: A list is a collection of elements that are ordered and changeable (mutable). In a list, elements can be added, removed, or modified at any time. Lists are created using square brackets []
Tuple: A tuple is also a collection of elements that are ordered but unchangeable (immutable). Once a tuple is created, its elements cannot be added, removed, or modified. Tuples are created using parentheses ().
Set: A set is a collection of unique elements that are unordered and changeable (mutable). In a set, each element must be unique. Sets are created using curly braces {} or the set() constructor.
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"
}
fav_tools = { 1:"Linux", 2:"Git", 3:"Docker", 4:"Kubernetes", 5:"Terraform", 6:"Ansible", 7:"Chef"}
favorite_tool_key = 3
favorite_tool = fav_tools[favorite_tool_key]
print("my favorite tool is",favorite_tool)
- 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.
cloud_providers = ["AWS","GCP","Azure"]
cloud_providers.append("Digital Ocean")
cloud_providers.sort()
print(cloud_providers)
.>>>>>>>>>THANKFOR READING GIVE YOU VALUABLE FEEDBACK <<<<<<<<<