Day 14 Task: Python Data Types and Data Structures for DevOps

🔹Data Types

  • Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data.

  • Since everything is an object in Python programming, data types are actually classes and variables are instance (object) 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: In Python, the "Number" data type is used to represent numeric values. There are three main types of numbers in Python: integers, floating-point numbers, and complex numbers.

    1. nteger (int): Integers are whole numbers without any decimal points. They can be positive or negative.

Example:

    # Declaring an integer variable
    num1 = 10

    # Performing arithmetic operations with integers
    result = num1 + 5
    print(result)  # Output: 15

    # Checking the data type of a variable
    print(type(num1))  # Output: <class 'int'>
  1. Floating-Point Number (float): Floating-point numbers are numbers with decimal points.

Example:

    # Declaring a floating-point variable
    num2 = 3.14

    # Performing arithmetic operations with floating-point numbers
    result = num2 * 2
    print(result)  # Output: 6.28

    # Checking the data type of a variable
    print(type(num2))  # Output: <class 'float'>
  1. Complex Number (complex): Complex numbers are numbers with both real and imaginary parts, represented in the form "a + bj" where "a" is the real part, and "b" is the imaginary part.

Example:

    # Declaring a complex variable
    num3 = 2 + 3j

    # Performing arithmetic operations with complex numbers
    result = num3 * (1 + 2j)
    print(result)  # Output: (-4+7j)

    # Checking the data type of a variable
    print(type(num3))  # Output: <class 'complex'>

Python's dynamic typing allows you to work with different number types seamlessly, and it automatically converts between different number types when needed during calculations.

  1. strings: In Python, the "String" data type is used to represent textual data, such as words, sentences, or characters. Strings are defined using single quotes (''), double quotes ("") or triple quotes (''' ''' or """ """).

    Example of creating strings:

     # Using single quotes
     string1 = 'Hello, world!'
    
     # Using double quotes
     string2 = "This is a string."
    
     # Using triple quotes for multiline strings
     string3 = '''Python is a versatile programming language.
     It is used for web development, data analysis, and more.'''
    
     print(string1+"",string2)
    
     print(type(string1))
    

    String methods are built-in functions that can be used to manipulate and work with strings. Here are some common string methods:

    1. len(): Returns the length of the string.
    string = "Hello, World!"
    length = len(string)
    print(length)  # Output: 13
  1. lower(): Converts the string to lowercase.
    string = "Hello, World!"
    lower_case = string.lower()
    print(lower_case)  # Output: hello, world!
  1. upper(): Converts the string to uppercase.
    string = "Hello, World!"
    upper_case = string.upper()
    print(upper_case)  # Output: HELLO, WORLD!
  1. strip(): Removes leading and trailing whitespaces from the string.
    string = "    Hello, World!   "
    stripped_string = string.strip()
    print(stripped_string)  # Output: "Hello, World!"
  1. split(): Splits the string into a list of substrings based on a delimiter.
    string = "apple,banana,orange"
    fruits = string.split(",")
    print(fruits)  # Output: ['apple', 'banana', 'orange']
  1. find(): Returns the index of the first occurrence of a substring in the string.
    string = "Hello, World!"
    index = string.find("World")
    print(index)  # Output: 7
  1. replace(): Replaces occurrences of a substring with another substring.
    string = "Hello, World!"
    new_string = string.replace("World", "Universe")
    print(new_string)  # Output: Hello, Universe!

These are just a few examples of the many useful methods available for working with strings in Python. Strings are an essential part of Python programming and are used extensively in various applications.

  1. Tuples: In Python, a tuple is a collection data type similar to a list, but it is immutable, meaning its elements cannot be changed once created. Tuples are defined using parentheses () and can contain elements of different data types, such as numbers, strings, or other tuples.

    Example of creating a tuple:

     # Empty tuple
     empty_tuple = ()
    
     # Tuple with elements
     fruit_tuple = ('apple', 'banana', 'orange')
    
     # Tuple with mixed data types
     mixed_tuple = (10, 'hello', 3.14)
    
     print(type(mixed_tuple))
    

    Tuples have some similarities with lists, such as indexing and slicing. However, unlike lists, you cannot modify, add, or remove elements from a tuple once it is created.

    Accessing elements of a tuple:

     fruit_tuple = ('apple', 'banana', 'orange')
     print(fruit_tuple[0])  # Output: 'apple'
     print(fruit_tuple[1])  # Output: 'banana'
     print(fruit_tuple[2])  # Output: 'orange'
    

    Tuple with a single element: If you want to create a tuple with a single element, you need to include a comma after the element. Otherwise, Python will treat it as a regular value, not a tuple.

     single_element_tuple = (42,)
     print(single_element_tuple)  # Output: (42,)
    

    Tuple unpacking: You can unpack a tuple and assign its elements to separate variables.

     fruits = ('apple', 'banana', 'orange')
     fruit1, fruit2, fruit3 = fruits
     print(fruit1)  # Output: 'apple'
     print(fruit2)  # Output: 'banana'
     print(fruit3)  # Output: 'orange'
    

    Tuple methods: Tuples have fewer built-in methods compared to lists because of their immutability. However, they share some methods with lists like count() and index().

     fruit_tuple = ('apple', 'banana', 'orange', 'apple')
    
     # count() method returns the number of occurrences of a specified element in the tuple.
     print(fruit_tuple.count('apple'))  # Output: 2
    
     # index() method returns the index of the first occurrence of a specified element.
     print(fruit_tuple.index('banana'))  # Output: 1
    

    Tuples are commonly used to represent fixed collections of items where immutability is desired. They are useful in scenarios where you want to ensure that the data remains unchanged throughout the program execution.

  2. Lists: In Python, a list is a mutable, ordered collection of elements. Lists are defined using square brackets [ ], and they can contain elements of different data types. Here's an explanation of lists with examples of their creation and commonly used methods:

    1. Creating a List: You can create a list by enclosing elements within square brackets and separating them with commas.

Example:

    fruits_list = ['apple', 'banana', 'orange', 'grapes']
    print(fruits_list)
    print(type(fruits_list))
  1. Accessing Elements: You can access elements in a list using their index. Indexing starts from 0 for the first element.

Example:

    print(fruits_list[0])  # Output: 'apple'
  1. Adding Elements: You can add elements to the list using append() to add at the end, or insert() to add at a specific index.

Example:

    fruits_list.append('kiwi')  # Adds 'kiwi' at the end of the list
    fruits_list.insert(1, 'mango')  # Adds 'mango' at index 1
  1. Removing Elements: You can remove elements from the list using remove() to remove by value or pop() to remove by index.

Example:

    fruits_list.remove('banana')  # Removes 'banana' from the list
    fruits_list.pop(2)  # Removes the element at index 2 ('orange')
  1. Updating Elements: You can update elements in a list by assigning new values to their index.

Example:

    fruits_list[0] = 'pear'  # Updates the element at index 0 to 'pear'
  1. List Slicing: You can extract a portion of the list using slicing.

Example:

    sliced_list = fruits_list[1:3]  # Returns ['mango', 'grapes']
  1. List Length: You can find the length of the list using the len() function.

Example:

    length = len(fruits_list)  # Returns 4 (after the previous modifications)
  1. List Concatenation: You can concatenate two lists using the + operator.

Example:

    new_list = fruits_list + ['pineapple', 'watermelon']
  1. List Sorting: You can sort a list using the sort() method.

Example:

    fruits_list.sort()  # Sorts the list in ascending order

These are some of the commonly used methods for lists in Python. Lists are versatile and widely used for various data manipulations due to their mutability and flexibility.

  1. Sets: In Python, a set is an unordered collection of unique elements. Sets are defined using curly braces { }, or by using the set() constructor. Sets do not allow duplicate elements, and they support various mathematical set operations. Here's an explanation of sets with examples of their creation and commonly used methods:

    1. Creating a Set: You can create a set by enclosing elements within curly braces { }.

Example:

    fruits_set = {'apple', 'banana', 'orange', 'grapes'}

You can also create a set using the set() constructor with an iterable like a list.

Example:

    numbers_list = [1, 2, 3, 3, 4, 5]
    numbers_set = set(numbers_list)  # Creates a set with unique elements [1, 2, 3, 4, 5]
  1. Adding Elements: You can add elements to a set using the add() method.

Example:

    fruits_set.add('kiwi')
  1. Removing Elements: You can remove elements from a set using the remove() method. If the element does not exist, it raises a KeyError. To avoid the KeyError, you can use the discard() method.

Example:

    fruits_set.remove('banana')
    fruits_set.discard('watermelon')  # No error if 'watermelon' is not present
  1. Set Operations: Sets support various mathematical set operations like union, intersection, difference, and symmetric difference.

    Union: Combines two sets and returns a new set with unique elements from both sets.

    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    union_set = set1 | set2  # Returns {1, 2, 3, 4, 5}

Intersection: Returns a new set with elements that are present in both sets.

    intersection_set = set1 & set2  # Returns {3}

Difference: Returns a new set with elements that are present in the first set but not in the second set.

    difference_set = set1 - set2  # Returns {1, 2}

Symmetric Difference: Returns a new set with elements that are present in either of the sets, but not in both.

    symmetric_diff_set = set1 ^ set2  # Returns {1, 2, 4, 5}
  1. Set Length: You can find the number of elements in a set using the len() function.

Example:

    length = len(fruits_set)
  1. Checking Membership: You can check if an element exists in a set using the in keyword.

Example:

    if 'apple' in fruits_set:
        print('Apple is in the set.')

Sets provide an efficient way to perform unique value operations and mathematical set operations in Python. Their unordered nature makes them suitable for scenarios where uniqueness matters, but the order of elements does not.

  1. Dictionaries: In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are defined using curly braces { } and consist of keys and their corresponding values. Each key in a dictionary must be unique. Dictionaries are widely used for data storage and retrieval, as they provide fast access to values based on their keys. Here's an explanation of dictionaries with examples of their creation and commonly used methods:

    1. Creating a Dictionary: You can create a dictionary by enclosing key-value pairs within curly braces { }.

Example:

        student = {'name': 'John', 'age': 25, 'roll_number': 'ABC123'}

You can also create a dictionary using the dict() constructor.

Example:

        student = dict(name='John', age=25, roll_number='ABC123')
  1. Accessing Values: You can access the values of a dictionary using the keys.

Example:

        print(student['name'])  # Output: 'John'
        print(student['age'])   # Output: 25
  1. Adding and Modifying Elements: You can add new key-value pairs or modify existing ones in a dictionary.

Example:

        student['marks'] = 85     # Adds a new key 'marks' with value 85
        student['age'] = 26       # Modifies the value of the existing key 'age' to 26
  1. Removing Elements: You can remove elements from a dictionary using the del keyword or the pop() method.

Example:

        del student['roll_number']  # Removes the key 'roll_number' from the dictionary
        marks = student.pop('marks')  # Removes the key 'marks' and returns its value
  1. Dictionary Methods: There are several useful methods available for dictionaries:

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

        all_keys = student.keys()
  • values(): Returns a list of all the values in the dictionary.
        all_values = student.values()
  • items(): Returns a list of key-value pairs (tuples) as a view object.
        all_items = student.items()
  • get(): Returns the value of a specified key. If the key does not exist, it returns a default value (or None if not specified).
        name = student.get('name')
  • clear(): Removes all key-value pairs from the dictionary, making it empty.
        student.clear()
  • update(): Updates the dictionary with key-value pairs from another dictionary or an iterable (e.g., list of tuples).
        student.update({'city': 'New York', 'marks': 90})

Dictionaries are powerful data structures in Python that provide a convenient way to store and access data with unique keys. They are commonly used for tasks that involve mapping keys to corresponding values.

🔹Data Structures

A data structure is a way of organizing and storing data in a computer so that it can be accessed and manipulated efficiently. Data structures play a crucial role in computer science and programming as they provide a blueprint for managing data in memory or on disk. Different data structures are designed to handle various types of data and perform specific operations effectively. Here are some common types of data structures:
Primitive Data Structures:

  1. Integer (int)

  2. Float (float)

  3. Character (char)

  4. Boolean (bool)

Non-Primitive Data Structures:

  1. Arrays

  2. Linked Lists

  3. Stacks

  4. Queues

  5. Trees

  6. Graphs

  7. Hash Tables

  8. Heaps

  9. Tries

Tasks

  1. Give the Difference between List, Tuple and set. Do Handson and put screenshots as per your understanding.

    1. List:

      • Mutable: Elements can be added, removed, or modified after the list is created.

      • Syntax: Created using square brackets [ ].

      • Ordered: Elements are stored in a specific order and can be accessed using indexes.

      • Duplicates: Allows duplicate elements.

      • Example: [1, 2, 3, "hello", True]

    2. Tuple:

      • Immutable: Once created, elements cannot be changed, added, or removed.

      • Syntax: Created using parentheses ( ).

      • Ordered: Similar to lists, elements are stored in a specific order and can be accessed using indexes.

      • Duplicates: Allows duplicate elements.

      • Example: (1, 2, 3, "hello", True)

    3. Set:

      • Mutable: Elements can be added or removed after the set is created, but elements cannot be modified.

      • Syntax: Created using curly braces { }, or with the set() constructor.

      • Unordered: Elements are not stored in a specific order, and you cannot access elements using indexes.

      • No Duplicates: Does not allow duplicate elements; it automatically removes duplicates.

      • Example: {1, 2, 3, "hello", True}

  2. Create below Dictionary and use Dictionary methods to print your favourite 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"
}
  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.