Day 14:Python Data Types and Data Structures for DevOps

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))

  1. 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

  2. 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:

  1. len(): Returns the length of the string.

  2. lower(): Converts all uppercase characters to lowercase.

  3. upper(): Converts all lowercase characters to uppercase.

  4. strip(): Removes any leading or trailing whitespace characters.

  5. split(): Splits the string into a list of substrings using a delimiter character. By default, the delimiter is a whitespace character.

  6. join(): Joins a list of strings into a single string using a specified delimiter character.

  7. replace(): Replaces a specified substring with another substring.

  8. startswith(): Returns True if the string starts with the specified prefix.

  9. endswith(): Returns True if the string ends with the specified suffix.

  10. 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.

  11. 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])

  1. 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 this

    Tuples 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)
    

  2. 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:

    1. append() - Adds an element to the end of the list

    2. extend() - Adds multiple elements to the end of the list

    3. insert() - Inserts an element at a specific position in the list

    4. remove() - Removes the first occurrence of an element from the list

    5. pop() - Removes and returns the last element of the list

    6. index() - Returns the index of the first occurrence of an element in the list

    7. count() - Returns the number of times an element appears in the list

    8. sort() - 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)

  1. 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 the set() function.

     dwarika={"aws","aws","aws","jenkins","docker","ansible"}
     print(dwarika)
    

    Sets have many built-in methods that you can use to manipulate them.

    1. add() - Adds an element to the set

    2. update() - Adds multiple elements to the set

    3. remove() - Removes an element from the set

    4. discard() - Removes an element from the set if it is a member. If the element is not a member, it does not raise an error.

    5. pop() - Removes and returns an arbitrary element from the set

    6. clear() - Removes all elements from the set

    7. union() - Returns the union of two sets (i.e., all the elements that are in either set)

    8. intersection() - Returns the intersection of two sets (i.e., all the elements that are in both sets)

    9. 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)
      

  1. 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 the dict() function.dwarika=

     {1:"aws",2:"gcp",3:"azure"}
     print(dwarika)
    

    Dictionaries have many built-in methods that you can use to manipulate them.

    1. get() - Returns the value associated with a key. If the key is not found, it returns a default value (None by default).

    2. keys() - Returns a list of all the keys in the dictionary

    3. values() - Returns a list of all the values in the dictionary

    4. items() - Returns a list of all the key-value pairs in the dictionary as tuples

    5. pop() - Removes and returns the value associated with a key

    6. update() - Adds or updates key-value pairs in the dictionary

    7. clear() - 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

  1. 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.

  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"
}
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)

    1. 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 <<<<<<<<<