Blog

  • Dictionary Methods in Python

    Dictionary is a built-in data type used in Python in order to store data in the form of ‘key: value’ pairs. Dictionaries are unordered (starting from Python 3.7, they preserve insertion order), mutable, and indexed collections where each key is unique and maps to a value. It is generally used to store related data, such as information associated with a specific entity or object, where the value can be retrieved easily based on the key.

    The Dictionary methods in Python are known as a collection of various functions that operate on a dictionary.

    Dictionary Methods in Python

    Python Dictionary Methods

    There are several Python Dictionary Methods that enable us to perform multiple tasks, such as manipulation, access, and transformation, with efficiency and precision.

    FunctionExplanation
    fromkeys()This method returns the dictionary with the key mapped to the value given in the “value” parameter.
    pop()This method is used to remove an element from the dictionary
    clear()This method is used to clear or delete all the elements from the dictionary.
    popitem()This method returns and removes the element that was added to the dictionary last. It is like last in, first out (LIFO).
    copy()This method returns a shallow copy of the dictionary.
    get()This method returns the value for the given key.
    setdefault()This method returns a value with a specified key. If there is no key, it will insert a key with the specified value.
    items()This returns all dictionary that has a value assigned.
    keys()This method returns a list of keys of the dictionary.
    update()This method is used to update the dictionary.
    values()This method returns a list of the dictionary values.

    Python Built-in Dictionary Methods

    1. Dictionary fromkeys() Method

    The dictionary fromkeys() method in Python returns the dictionary with the key mapped to the value given in the ‘value’ parameter. It does not change anything in the given dictionary; instead, it creates a new dictionary in the sequence of the specified values.

    Syntax:

    The syntax of the fromkeys() method is shown below:

    dict.fromkeys(keys, value)  

    Parameters:

    • keys: This parameter represents the keys to be transformed into a dictionary.
    • value: It is optional. It represents the value for all your keys. The default value is set to None.

    Note: The value that you specify in the value parameter is assigned to all the keys of the dictionary.

    Returns: This method returns a dictionary with keys. If the keys are mapped to none, it returns no value; otherwise, it returns the respective value provided for that field.

    Example: Dictionary fromkeys() Method

    Let us see an example to understand the working of the fromkeys() method in Python.

    Example

    # given set of keys  
    
    keys = {'a', 'e', 'i', 'o', 'u'}  
    
    # creating a dictionary  using fromkeys()  
    
    dict_1 = dict.fromkeys(keys)  # not specified any value  
    
    print("Dictionary 1 (without values):", dict_1) # set default values to none  
    
    # initializing a variable to store a value  
    
    value = 'vowel'  
    
    dict_2 = dict.fromkeys(keys, value) # specifying a default value  
    
    print("Dictionary 2 (with default value):", dict_2)

    Output:

    Dictionary 1 (without values): {'o': None, 'i': None, 'a': None, 'e': None, 'u': None}
    Dictionary 2 (with default value): {'o': 'vowel', 'i': 'vowel', 'a': 'vowel', 'e': 'vowel', 'u': 'vowel'}
    

    2. Dictionary pop() Method

    In Python, the dictionary pop() method is used to remove an element from the dictionary. This method removes the element from the specified key in the given list.

    If the particular key is present in the dictionary, it is removed from the dictionary, and the value is returned. If the specified key is not present, it raises a KeyError error.

    Syntax:

    The syntax of the pop() method is shown below:

    dictionary_name.pop(key, default_value)

    Parameters:

    • key:A key to delete the value associated with it.
    • default_value:If the key is not present, the default value is returned.

    Return: It removes and returns the value associated with the specified key.

    Example: Dictionary pop() Method

    Let us see an example to understand the working of the pop() method in Python.

    Example

    # simple example of Python dictionary pop() method  
    
    # given dictionary    
    
    fruits = {    
    
        'apple': 20,     
    
        'banana': 14,     
    
        'watermelon': 2,     
    
        'kiwi': 12,     
    
        'oranges': 24    
    
        }    
    
    print("Given Dictionary:", fruits)    
    
      # using the pop() method to remove the specified key    
    
    popped_value = fruits.pop('kiwi')    
    
    print("Popped Value:", popped_value)    
    
    print("Updated Dictionary:", fruits)

    Output:

    Given Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}
    Popped Value: 12
    Updated Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'oranges': 24}
    

    Explanation

    In the above example, we are given a dictionary. We used the pop() method to remove the specified key from the dictionary. As a result, the key is removed, and the value associated with that key is returned.

    3. Dictionary clear() Method

    The Dictionary clear() method in Python is used to clear, delete, or remove all the elements from the dictionary. It removes everything in key-value pairs and makes the dictionary empty.

    Syntax:

    The syntax of the clear() method is shown below:

    NameoftheDictionary.clear()

    Parameters: This method does not accept any parameters.

    Return Value: This method does not return any value.

    Example: Dictionary clear() Method

    Let us see an example to understand the working of the clear() method in Python.

    Example

    new_dictionary = {'1': 'Welcome', '2': 'to', '3': 'Lean Python App'}  
    
    new_dictionary.clear()  
    
    print("Printing the dictionary after .clear() method: \n", new_dictionary)

    Output:

    Printing the dictionary after .clear() method:
    {}
    

    Explanation

    In the above example, we are given a dictionary. We used the clear() method to remove all the elements from the dictionary. As a result, all the elements are removed, and an empty dictionary is returned.

    4. Dictionary popitem() Method

    The popitem() method in Python is used to remove the item (key and value pair) that was last added to the dictionary. keyError is raised, just in case the dictionary is empty.

    Syntax:

    The syntax of the popitem() method is shown below:

    NameoftheDictionary.popitem()

    Parameters: This method does not accept any parameters.

    Return Value: This method returns a new dictionary after removing the last added item in the dictionary.

    Example: Dictionary popitem() Method

    Let us see an example to understand the working of the popitem() method in Python.

    Example

    dictionary_data = {'Welcome': 1, 'to': 2, 'Learn Python App': 3}  
    
    item = dictionary_data.popitem()  
    
    print("The item is:",item)    
    
    print("The dictionary obtained is:",dictionary_data)

    Output:

    The item is: ('Learn Python App', 3)
    The dictionary obtained is: {'Welcome': 1, 'to': 2}
    

    Explanation

    In the above example, we are given a dictionary. We used the popitem() method to remove the last added item from the dictionary. As a result, a new dictionary is returned after removing the last added item.

    5. Dictionary copy() Method

    The copy() method in Python is used to create and return a shallow copy of the dictionary.

    A shallow copy creates a new object that looks exactly like the original object-s structure, apart from its nested contents. The top-level properties are copied into a new dictionary, while any referenced objects inside it still point to the same memory locations as those in the original. In conclusion, only the container is duplicated while the overall reference values remain the same.

    Syntax:

    The syntax of the copy() method is shown below:

    NameoftheDictionary.copy()

    Parameters: This method does not accept any parameters.

    Return Value: This method returns a shallow copy of the present dictionary.

    Example: Dictionary copy() Method

    Let us see an example to understand the working of the copy() method in Python.

    Example

    first_dictionary = {'Name': 'Learn Python App', 'Topic': 'Python Copy Method'};  
    
    second_dictionary = first_dictionary.copy()  
    
    print ("New Dictionary : %s" %  str(second_dictionary))

    Output:

    New Dictionary : {'Name': 'Learn Python App', 'Topic': 'Python Copy Method'}

    Explanation

    In the above example, we are given a dictionary named first_dictionary. Then created a shallow copy of this dictionary in the new dictionary named second_dictionary and printed the output.

    Example: Updating the elements of a Dictionary

    Let us see an example of updating the elements of a dictionary using the copy() method:

    Example

    1. first_dictionary = {1: ‘Learn Python App’, 2: ‘Python Dictionary Methods’, 3: [2, 0, 5]}  
    2. print(“The given dictionary is: “, first_dictionary)  
    3. # using copy() method to copy  
    4. new_dictionary = first_dictionary.copy()  
    5. print(“The new copied dictionary is: “, new_dictionary)  
    6. # Updating the elements in the second dictionary  
    7. new_dictionary[1] = ‘Python Copy Method’  
    8. # updating the items in the list   
    9. new_dictionary[3][2] = 404   
    10. print(“The updated dictionary is: “, new_dictionary)  

    Output:

    The given dictionary is: {1: 'Learn Python App', 2: 'Python Dictionary Methods', 3: [2, 0, 5]}
    The new copied dictionary is: {1: 'Learn Python App', 2: 'Python Dictionary Methods', 3: [2, 0, 5]}
    The updated dictionary is: {1: 'Python Copy Method', 2: 'Python Dictionary Methods', 3: [2, 0, 404]}
    

    Explanation

    In the above example, we are given a dictionary named first_dictionary. We copied the elements of this dictionary into a second but new dictionary named new_dictionary and then printed it.

    After this, we updated to elements of the new_dictionary and printed the output.

    6. Dictionary get() Method

    The get() method in Python is used to get the value of the key specified by the user. If the key is not present in the dictionary, it will return None.

    Syntax:

    The syntax of the get() method is shown below:

    NameoftheDictionary.get(key, value)

    Parameters:

    • key: The key is specified by the user, and it-s to be searched in the dictionary
    • value: The value assigned to the specified key is returned. If the key does not exist, it will return None.

    Example: Dictionary get() Method

    Let us see an example to understand the working of the get() method in Python.

    Example

    car_details = {  
    
      "brand": "Tata",  
    
      "model": "Sierra",  
    
      "year": 2025  
    
    }  
    
    a = car_details.get("model")  
    
    print(a)

    Output:

    Sierra

    Explanation

    In the above example, we have a dictionary named car_details consisting of details of cars. We used the get() method to extract the -model- key from the dictionary.

    Example: When the Key does not exist

    Let us see an example to see what happens when the key does not exist while using the get() method:

    Example

    car_details = {  
    
      "brand": "Tata",  
    
      "model": "Sierra",  
    
      "year": 2025  
    
    }  
    
    a = car_details.get("kilometres_driven")  
    
    print(a)

    Output:

    None

    Explanation

    In the above example, we have a dictionary named car_details in which we have the details of a car, such as brand, model, and year.

    By using the get() method, we try to extract the value of the key “kilometres_driven,” but as this key does not exist in the dictionary, the get() function returns None instead of raising an error. At last, none was returned as the output.

    7. Dictionary setdefault() Method

    The setdefault() method in Python is used to return a value with a specified key. If there is no key, it will insert a key with the specified value. None is the default value of the key.

    Syntax:

    The syntax of the setdefault() method is shown below:

    NameoftheDictionary.setdefault(key, default=None)

    Parameters

    • key: The key is specified by the user, and it-s to be searched in the dictionary
    • value: If the key is not found, this value is destined to be returned. The default value is None.

    Example: Dictionary setdefault() method

    Let us see an example to understand the working of the setdefault() method in Python.

    Example

    #Creating a dictionary  
    
    dictionary = {'Car Brand': 'Tata', 'Model': 'Sierra'}  
    
    # printing the first result  
    
    print ("Value : %s" %  dictionary.setdefault('Model'))

    Output:

    Value : Sierra

    Explanation

    In the above example, we have a dictionary consisting of Car Brand and Model keys with their values, Tata and Sierra, respectively. Then we printed the Model key from the dictionary, and it returned -Sierra- as the output.

    Example: None Default Value

    Let us see an example to understand the significance of the None default value.

    Example

    #Creating a dictionary  
    
    dictionary = {'Car Brand': 'Tata', 'Model': 'Sierra'}  
    
    #key doesn't exist   
    
    print ("Value : %s" %  dictionary.setdefault('Age'))

    Output:

    Value : None

    Explanation

    In the above example, we have a dictionary consisting of Car Brand and Model keys with their values, Tata and Sierra, respectively. Then we tried to print the value of key -Age-, but since it does not exist, the default key, which is None, is returned.

    8. Dictionary items() Method

    The items() method in Python is used to return all the items of the dictionary that have a value assigned.

    When we update the dictionary, the items that are returned also get changed. As we know, that dictionary Dictionaries are unordered (starting from Python 3.7, they preserve insertion order), mutable, and indexed collections where each key is unique and maps to a value. It is generally used to store related data, such as information associated with a specific entity or object, where the value can be retrieved easily based on the key.

    Syntax:

    The syntax of the items() method is shown below:

    The following is the syntax of the items() method:

    NameoftheDictionary.items()

    Parameters: This method does not accept any parameters.

    Return Value: The item() returns the output in the form of a list with key-value pairs in a tuple.

    Example: Dictionary items() method

    Let us see an example to understand the working of the items() method in Python.

    Example

    dictionary = {'A': 'Learn Python App', 'B': 'Python', 'C': 'Dictionary', 'D': 'Methods'}  
    
    # using items() to get all key-value pairs  
    
    items = dictionary.items()  
    
    print(items)

    Output:

    dict_items([('A', 'Learn Python App'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])

    Explanation

    In the above example, we have created a dictionary and printed all items present in key-value pairs in a tuple, which is present inside a dictionary.

    Example: Updating the Dictionary

    Let us see an example of updating the dictionary using the items() method in Python

    Example

    dictionary = {'A': 'Learn Python App', 'B': 'Python', 'C': 'Dictionary', 'D': 'Methods'}  
    
    # using items() to get all key-value pairs  
    
    items = dictionary.items()  
    
    print(items)  
    
    #updating the dictionary  
    
    dictionary['A'] = 'Welcome to Learn Python App'  
    
    print("Dictionary after updating: ", items)

    Output:

    dict_items([('A', 'Learn Python App'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])
    Dictionary after updating: dict_items([('A', 'Welcome to Learn Python App'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])
    

    Explanation

    In the above example, we have created a dictionary and printed all items present in key-value pairs in a tuple, which is present inside a dictionary. Then we updated the value of the ‘A’ key from ‘Tpoint Tech’ to ‘Welcome to TpointTech’ and printed the updated dictionary.

    9. Dictionary keys() Method

    The method is used to extract and return the list of keys of the dictionary.

    Syntax:

    The syntax of the keys() method is shown below:

    NameoftheDictionary.keys()

    Parameters: This method does not accept any parameters.

    Return Value: The item() method returns the return the list of keys of the dictionary.

    Example: keys() method

    Let us see an example to understand the working of the keys() method in Python.

    Example

    #Creating a dictionary  
    
    car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}  
    
    # extracts and prints the keys of the dictionary  
    
    keysmethod= car_details.keys()  
    
    print(keysmethod)

    Output:

    dict_keys(['Car Brand', 'Model', 'Year'])

    Explanation

    In the above example, we have a dictionary car_details with the keys and values.  We use the keys() method to extract and print the keys only, which are ‘Car Brand’, ‘Model’, and ‘Year’.

    Example: Updating the Dictionary

    Let us see an example of updating the dictionary using the keys() method in Python.

    Example

    #Creating a dictionary  
    
    car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}  
    
    # extracts and prints the keys of the dictionary  
    
    keysmethod= car_details.keys()  
    
    print('Before the update of dictionary:', keysmethod)  
    
    #updating the dictionary  
    
    # adding an element to the dictionary  
    
    car_details.update({'price': '11.99 Lakhs only'})  
    
    # prints the updated dictionary  
    
    print('Dictionary after the update:', keysmethod)

    Output:

    Before the update of the dictionary: dict_keys(['Car Brand', 'Model', 'Year'])
    Dictionary after the update: dict_keys(['Car Brand', 'Model', 'Year', 'price'])
    

    Explanation

    In the above example, we have a dictionary car_details with the keys and values.  We use the keys() method to extract and print the keys only, which are ‘Car Brand’, ‘Model’, and ‘Year’. Then we added an element and printed the keys of the updated dictionary, which consisted of the addition of -price-.

    10. Dictionary values() Method

    The values() method allows us to return a view object consisting of all values from the dictionary, which can be accessed and iterated efficiently.

    Syntax:

    The syntax of the values() method is shown below:

    NameoftheDictionary.values()

    Parameters: This method does not accept any parameters.

    Return Value: The values() method returns a list of the dictionary values.

    Example: Dictionary values() Method

    Let us take a look at an example showing how to use the values() method in Python.

    Example

    #Creating a dictionary  
    
    car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}  
    
    # extracts and prints the values of the dictionary  
    
    valuesmethod= car_details.values()  
    
    print(valuesmethod)

    Output:

    dict_values(['Tata', 'Sierra', 2025])

    Explanation

    In the above example, we have a dictionary car_details with the keys and values.  We use the values() method to extract and print the values only, which are ‘Tata’, ‘Sierra’, and 2025.

    Example: Updating the Dictionary

    Let us take a look at an example of updating the dictionary using the values() method in Python.

    Example

    #Creating a dictionary  
    
    car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}  
    
    # extracts and prints the values of the dictionary  
    
    valuesmethod= car_details.values()  
    
    print("The values of the dictionary before appending are: ", valuesmethod)  
    
    # Appending an item to the dictionary  
    
    car_details['Fuel Type'] = 'Petrol'  
    
    # Printing the result  
    
    print ("The values of the dictionary after appending are: ", valuesmethod)

    Output:

    The values of the dictionary before appending are: dict_values(['Tata', 'Sierra', 2025])
    The values of the dictionary after appending are: dict_values(['Tata', 'Sierra', 2025, 'Petrol'])
    

    Explanation

    In the above example, we have a dictionary car_details with the keys and values.  We use the values() method to extract and print the values of the dictionary before updating, which are ‘Tata’, ‘Sierra’, and 2025.

    After that, we append an item in the dictionary, where we created a new key named -Fuel_Type,- and its value is Petrol. Then, we printed the values, and the output was: ([‘Tata’, ‘Sierra’, 2025, ‘Petrol’]).

    11. Dictionary update() Method

    The update() method is used to update the items in the dictionary or an iterable object with key-value pairs.

    Syntax:

    The syntax of the update() method is shown below:

    NameoftheDictionary.update([other])

    Parameters: This method accepts the elements that must be replaced with a dictionary or an iterable pair of key/value.

    Return Value: The values() return the dictionary or iterable pairs of keys and values with updated elements.

    Example: Dictionary update() Method

    Let us see a simple example showing the use of the update() method in Python.

    Example

    # using the update() method in Dictionary  
    
    # Dictionary with three items  
    
    first_dictionary = {'A': 'LearnPython', 'B': 'Python', }  
    
    second_dictionary = {'B': 'Dictionary', 'C': 'Methods'}  
    
    # updating first dictionary  
    
    first_dictionary.update(A='Welcome to LearnPython')  
    
    print(first_dictionary)  
    
    #updating second dictionary  
    
    second_dictionary.update(B='We are learning Dictionary')  
    
    print(second_dictionary)

    Output:

    {'A': 'Welcome to LearnPython', 'B': 'Python'}
    {'B': 'We are learning Dictionary', 'C': 'Methods'}
    

    Explanation

    In the above example, we have two dictionaries, first_dictionary and second_dictionary. The update() method was used to update the values of key A to -Welcome to Tpoint Tech- from -Tpoint Tech- and key B to -We are learning Dictionary- from -Dictionary- in both dictionaries, respectively.

    Example: Updating the dictionary with Keyword Arguments

    Let us take a look at an example of updating the dictionary with keyword arguments in Python.

    Example

    #updating the dictionary with only keyword arguments  
    
    # Here we have only one dictionary  
    
    dictionary = {'A': 'Lean'}  
    
    # Update the Dictionary with an iterable  
    
    dictionary.update(B='Python', C='App')  
    
    print(dictionary)

    Output:

    'A': 'Learn', 'B': 'Python', 'C': 'App'}
  • Python Dictionaries

    Python Dictionary is one of the built-in data types used to store data in ‘key: value’ pairs. The dictionary is an unorderedmutable and indexed collection where each key is unique and maps to a value. It is often used to store related data, like information associated with a particular entity or object, where we can easily get value on the basis of its key.

    Python Dictionaries

    Let us take a look at a simple example of a dictionary.

    Example

    # creating a Dictionary  
    
    D = {1: 'Learn', 2: 'Python', 3: 'from', 4: 'Learn', 5: 'Python', 6: 'App'}  
    
      
    
    print(D)

    Output:

    {1: 'Learn', 2: 'Python', 3: 'from', 4: 'Learn', 5: 'Python', 6: 'App'}

    Explanation:

    In the above example, we have created a simple dictionary consisting of multiple ‘key: value’ pairs.

    As we can observe, a dictionary in Python is a mapping data type where the value of one object maps to another. In order to establish the mapping between a key and a value, we have used the colon ‘:’ symbol between the two.

    Characteristics of Python Dictionary

    A dictionary in Python is a data type with the following characteristics:

    • Mutable: Dictionaries can be modified after initialization allowing us to add, remove or update ‘key: value’ pairs.
    • Unordered: Python dictionary does not follow a particular order to store items. However, starting from Python 3.7, the feature for the dictionary to maintain the insertion order of the items was added.
    • Indexed: Unlike lists or tuples, which are indexed by position, dictionaries use keys to access values, offering faster and more readable data retrieval.
    • Unique Keys: Each key in a dictionary must be unique. If we try to assign a value to an existing key, the old value will be replaced by the new one.
    • Heterogeneous: Keys and values in a dictionary can be of any type.

    Creating a Dictionary

    In Python, we can create a dictionary by enclosing the sequence of ‘key: value’ pairs with curly braces separated by commas. As an alternate option, we can use the Python’s built-in dict() function.

    Python Example to Create a Dictionary

    Here is a simple example showing both ways of creating a dictionary in Python.

    Example

    # simple example to create python dictionary  
    
      
    
    # creating dictionaries  
    
    dict_zero = {}     # empty dictionary  
    
    dict_one = {"name": "Lucy", "age": 19, "city": "New Jersey"} # using {}  
    
    dict_two = dict(name = "John", age = 21, city = "Havana")  # using dict()  
    
      
    
    # printing the results  
    
    print("Empty Dictionary:", dict_zero)  
    
    print("Dictionary 1 (created using {}):", dict_one)  
    
    print("Dictionary 2 (created using dict()):", dict_two)

    Output:

    Empty Dictionary: {}
    Dictionary 1 (created using {}): {'name': 'Lucy', 'age': 19, 'city': 'New Jersey'}
    Dictionary 2 (created using dict()): {'name': 'John', 'age': 21, 'city': 'Havana'}
    

    Explanation:

    The above example shows different ways to create dictionaries in Python. We have also seen how to create an empty dictionary.

    Note: The dict() function can also be used to transform an existing data type into a dictionary.

    Accessing Dictionary Items

    In Python, we can access the value of a dictionary item by enclosing that particular key with square brackets ‘[]’. Another way to access dictionary items is by the use of the get() method.

    Python Example to Access a Dictionary

    The following is a simple example showing the ways to access dictionary items in Python.

    Example

    # simple example to access dictionary items  
    
      
    
    # given dictionary  
    
    dict_x = {  
    
        "name": "Sachin",   
    
        "age": 18,   
    
        "gender": "male",   
    
        "profession": "student"  
    
        }  
    
      
    
    print("Person's Details")  
    
    # accessing dictionary items using keys  
    
    print("Name:", dict_x["name"])  
    
    print("Age:", dict_x["age"])  
    
      
    
    # accessing dictionary items using get()  
    
    print("Gender:", dict_x.get("gender"))  
    
    print("Profession:", dict_x.get("profession"))

    Output:

    Person's Details
    Name: Sachin
    Age: 18
    Gender: male
    Profession: student
    

    Explanation:

    Here, we have accessed the different values of the dictionary items using the square brackets and get() method.

    Adding Items to a Dictionary

    The dictionary is a mutable data type that allows us to add an item to it. This can be done by assigning a value to a new key.

    Python Example to Add Items to a Dictionary

    Let us take a look at a simple example showing how to add items to a Python dictionary.

    Example

    # simple example to add item to dictionary  
    
      
    
    # given dictionary  
    
    dict_x = {  
    
        "name": "Sachin",   
    
        "age": 18,   
    
        "gender": "male",   
    
        "profession": "student"  
    
        }  
    
      
    
    print("Given Dictionary:", dict_x)  
    
      
    
    # adding an item to the dictionary  
    
    dict_x["country"] = "India"  
    
      
    
    print("Updated Dictionary:", dict_x)

    Output:

    Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student'}
    Updated Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}
    

    Explanation:

    In this example, we have added a new ‘key: value’ pair to the dictionary using the assignment operator.

    Removing Items from a Dictionary

    Python offers multiple ways to remove items from a given dictionary, such as:

    • del: This keyword is used to remove an item by key.
    • pop(): This method is used to remove an item by key. It also returns the value of the removed item.
    • popitem(): This method removes and returns the last ‘key: value’ pair.
    • clear(): This method is used to remove all items from the dictionary.

    Python Example to Remove Items from a Dictionary Using Different Methods

    Here is an example showing the use of different methods to remove items from a Python dictionary.

    Example

    # simple example to remove items from a dictionary  
    
      
    
    # given dictionary  
    
    dict_x = {  
    
        "name": "Sachin",   
    
        "age": 18,   
    
        "gender": "male",   
    
        "profession": "student",  
    
        "country": "India"  
    
        }  
    
      
    
    print("Given Dictionary:", dict_x)  
    
      
    
    # removing items from the dictionary  
    
    del dict_x['age']     # using del  
    
    print("Updated Dictionary (Removed 'age'):", dict_x)  
    
      
    
    popped_value = dict_x.pop('gender')  # using pop()  
    
    print("Updated Dictionary (Removed 'gender'):", dict_x)  
    
    print("Popped Value:", popped_value)  
    
      
    
    popped_item = dict_x.popitem()  # using popitem()  
    
    print("Updated Dictionary (Removed last item):", dict_x)  
    
    print("Popped Item:", popped_item)  
    
      
    
    dict_x.clear()  # using clear()  
    
    print("Update Dictionary (Removed all items):", dict_x)

    Output:

    Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}
    Updated Dictionary (Removed 'age'): {'name': 'Sachin', 'gender': 'male', 'profession': 'student', 'country': 'India'}
    Updated Dictionary (Removed 'gender'): {'name': 'Sachin', 'profession': 'student', 'country': 'India'}
    Popped Value: male
    Updated Dictionary (Removed last item): {'name': 'Sachin', 'profession': 'student'}
    Popped Item: ('country', 'India')
    Update Dictionary (Removed all items): {}
    

    Explanation:

    In this example, we are given a dictionary. We have used several methods like del keyword, pop(), popitem(), and clear() methods to remove the items from the dictionary.

    Changing Dictionary Items

    In Python, we can change the values of an item in the dictionary by referring to its key.

    Python Example to Change Dictionary Items

    Let us take a simple example to understand how to change dictionary items in Python.

    Example

    # simple example to change dictionary items  
    
      
    
    # given dictionary  
    
    dict_x = {  
    
        "name": "Sachin",   
    
        "age": 18,   
    
        "gender": "male",   
    
        "profession": "student",  
    
        "country": "India"  
    
        }  
    
      
    
    print("Given Dictionary:", dict_x)  
    
      
    
    # changing dictionary items  
    
    dict_x["age"] = 20  
    
    dict_x["profession"] = "developer"  
    
      
    
    print("Updated Dictionary:", dict_x)

    Output:

    Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}
    Updated Dictionary: {'name': 'Sachin', 'age': 20, 'gender': 'male', 'profession': 'developer', 'country': 'India'}
    

    Explanation:

    In this example, we have used the assignment operator to change the value of existing keys in the given dictionary. As a result, the dictionary items are updated.

    Iterating Through a Dictionary

    Starting from Python 3.7, a dictionary is an ordered collection of items; therefore, it maintains the order of its items. We can iterate through dictionary keys using the ‘for’ loop, as shown in the following example.

    Example

    # simple example to iterate through a dictionary  
    
      
    
    # given dictionary  
    
    dict_x = {  
    
        "Name": "Sachin",   
    
        "Age": 18,   
    
        "Gender": "Male",   
    
        "Profession": "Student",  
    
        "Country": "India"  
    
        }  
    
      
    
    print("Items in Dictionary:")  
    
    # iterating through a dictionary using for loop  
    
    for key in dict_x:  
    
      value = dict_x[key]  
    
      print(key, "->", value)

    Output:

    Items in Dictionary:
    Name -> Sachin
    Age -> 18
    Gender -> Male
    Profession -> Student
    Country -> India
    

    Explanation:

    In the above example, we have used the ‘for’ loop to iterate through the keys in dictionary and accessed the value for each key.

    Finding Length of a Dictionary

    In order to find the length of a dictionary, we can use Python’s built-in function called len(). This function will return the total number of ‘key: value’ pairs present in a dictionary, allowing us to determine the size of the dictionary efficiently.

    Python Example to Find the Length of a Dictionary

    Let us see the following example showing the use of the len() function in determining the length of a Python dictionary.

    Example

    # simple example to determine length of a dictionary  
    
      
    
    # given dictionary  
    
    employees_info = {  
    
        "John": "Sr. Software Developer",  
    
        "Irfan": "UI/UX Designer",  
    
        "Lucy": "Human Resource Manager",  
    
        "Peter": "Team Lead",  
    
        "Johnson": "Business Developer",  
    
        }  
    
      
    
    print("Given Data:", employees_info)  
    
    # finding length of the dictionary  
    
    print("Size of Data:", len(employees_info)) # using len()

    Output:

    Given Data: {'John': 'Sr. Software Developer', 'Irfan': 'UI/UX Designer', 'Lucy': 'Human Resource Manager', 'Peter': 'Team Lead', 'Johnson': 'Business Developer'}
    Size of Data: 5
    

    Explanation:

    In the above example, we have used the len() function in order to find out how many items are in the given dictionary.

    Dictionary Membership Test

    We can use the ‘in’ or ‘not in’ operators in order to check whether a key exists in a dictionary. Here’s a simple example that shows how to see if a specified key is part of a dictionary in Python.

    Example

    # simple example to check membership   
    
    dict_y = {  
    
        'fruit': 'apple',  
    
        'vegetable': 'onion',  
    
        'dry-fruit': 'resins'  
    
    }  
    
    # using 'in' and 'not in' operators  
    
    print("Is 'fruit' a member of 'dict_y'?:", 'fruit' in dict_y)  
    
    print("Is 'beverage' a member of 'dict_y'?:", 'beverage' in dict_y)  
    
    print("Is 'beverage' NOT a member of 'dict_y'?:", 'beverage' not in dict_y)

    Output:

    Is 'fruit' a member of 'dict_y'?: True
    Is 'beverage' a member of 'dict_y'?: False
    Is 'beverage' NOT a member of 'dict_y'?: True
    

    Explanation:

    In this example, we have used the ‘in’ and ‘not in’ operators to check if the specified keys are present in the given dictionary. The ‘in’ operator returns the Boolean value after checking if the key exists in the dictionary, whereas the ‘not in’ operator returns the Boolean value after checking if the key does not exist in it.

    Dictionary Methods in Python

    Python offers several dictionary methods in order to manipulate the data of a dictionary. These methods are commonly used to add, update, delete, and return elements from the dictionaries. Some of these methods are as follows:

    Dictionary MethodDescription
    get()This method returns the value associated with a specific key.
    update()This method is utilized to add a new item to the dictionary or update the value of an existing key.
    copy()This method is utilized to return a copy of the dictionary.
    pop()This method removes the item with the given key from the dictionary.
    popitem()This method is utilized to return the last inserted key and value as a tuple.
    clear()This method removes all items from the dictionary.
    keys()This method returns all the keys in the dictionary.
    values()This method is utilized to return all the values in the dictionary.

    Conclusion

    Python dictionaries are a fundamental and highly flexible data type that allow us to store, access, and manipulate data using ‘key: value’ pairs. They are optimized for fast lookups and can handle everything from simple mappings to complex nested data. Whether we are managing configuration files, processing JSON, or building data-driven applications, mastering dictionaries is essential for writing efficient and clean line of codes in real-world scenarios.

  • Python Set Methods

    In Python, set methods are used to manipulate the data of a set in an effective and efficient way. These methods allow us to add, remove, and update the elements of sets. Sets in Python, is an unordered and mutable data type allowing us to store a collection of unique objects in a single variable.

    Let us take a look at various Set methods available in Python.

    MethodDescription
    add()This method is utilized to add a data element to the set.
    clear()This method is utilized to remove all data elements from the set.
    copy()This method is used to return a shallow copy of the set.
    discard()This method is used to remove a data element if it is a member. It will not return any error if the specified element is not found in the set.
    remove()This method is utilized to remove a data element from the given set; however, it raises a KeyError if the specified element is not found.
    pop()This method is used to remove and return an arbitrary element.
    update()This method is utilized to add elements from other sets or iterables.

    1) add() Method

    The add() method is used to add a new element to a set while ensuring uniqueness. If the passed element already exists, the set remains unchanged.

    Syntax:

    The syntax of the add() method is shown below:

    set_name.add(item)  

    Python Set’s add() Method Example

    We will now look at a simple example showing the use case of set’s add() method in Python.

    Example

    # python program to show the use of set add() method    
    
        
    
    # creating a set    
    
    set_of_fruits = {'apple', 'mango', 'banana', 'orange', 'guava'}  
    
    # printing the set  
    
    print("Set of Fruits:", set_of_fruits)    
    
        
    
    # using the add() method    
    
    set_of_fruits.add('grapes')  
    
        
    
    # printing the updated set    
    
    print("Updated Set of Fruits:", set_of_fruits)

    Output:

    Set of Fruits: {'banana', 'orange', 'apple', 'guava', 'mango'}
    Updated Set of Fruits: {'banana', 'orange', 'apple', 'guava', 'mango', 'grapes'}
    

    Explanation:

    In the above example, we have used the add() method to add a new element ‘grapes’ to the given set.

    2) clear()

    The clear() method is utilized to remove all the elements from the given set.

    Syntax:

    The following is the syntax of the clear() method:

    set_name.clear()  

    Python Set’s clear() Method Example

    We will now look at an example to understand the working of set’s clear() method in Python.

    Example

    # python program to show the use of set clear() method    
    
        
    
    # creating a set  
    
    game_set = {'football', 'cricket', 'volleyball', 'basketball', 'hockey'}  
    
    # printing the set  
    
    print("Given Set:", game_set)  
    
      
    
    # using the clear() method  
    
    game_set.clear()  
    
      
    
    # printing the updated set    
    
    print("Updated Set:", game_set)

    Output:

    Given Set: {'basketball', 'hockey', 'football', 'cricket', 'volleyball'}
    Updated Set: set()
    

    Explanation:

    In the above example, we have used the clear() method to remove all the elements from the given set.

    3) copy()

    The copy() method is used to return a shallow copy of the set in Python.

    Syntax:

    Here is the syntax of the copy() method:

    set_name.copy()  

    Python Set’s copy() Method Example

    We will now see an example showing the use of set’s copy() method in Python.

    Example

    # python program to show the use of set copy() method    
    
        
    
    # creating a set  
    
    vegetable_set = {'potato', 'eggplant', 'tomato', 'cabbage', 'broccoli'}  
    
    # printing the set  
    
    print("Given Set:", vegetable_set)  
    
      
    
    # using the copy() method  
    
    dummy_set = vegetable_set.copy()  
    
      
    
    # printing the updated set    
    
    print("Dummy Set:", dummy_set)

    Output:

    Given Set: {'potato', 'tomato', 'broccoli', 'eggplant', 'cabbage'}
    Dummy Set: {'potato', 'tomato', 'broccoli', 'eggplant', 'cabbage'}
    

    Explanation:

    In this example, we have used the copy() method to create a shallow copy of the given set.

    4) discard()

    The discard() method is utilized to remove the elements from the set. This method does not return any error in case the particular element is not found in the given set.

    Syntax:

    The following is the syntax of the discard() method:

    set_name.discard(item)  

    Python Set’s discard() Method Example

    We will now look at a simple example showing the usage of set’s discard() method in Python.

    Example

    # python program to show the use of set discard() method    
    
        
    
    # creating a set  
    
    beverage_set = {'milk', 'juice', 'soda', 'tea', 'coffee'}  
    
    # printing the set  
    
    print("Given Set:", beverage_set)  
    
      
    
    # using the discard() method  
    
    beverage_set.discard('soda')  
    
      
    
    # printing the updated set  
    
    print("Updated Set:", beverage_set)

    Output:

    Given Set: {'juice', 'milk', 'coffee', 'tea', 'soda'}
    Updated Set: {'juice', 'milk', 'coffee', 'tea'}
    

    Explanation:

    In this example, we have used the discard() method to remove the specified element from the given set.

    5) remove()

    The remove() method is utilized to delete the specified element from the set. It will raise an error if the passed element does not exist in the given set.

    Syntax:

    Here is the syntax of the remove() method:

    set_name.remove(item)  

    Python Set’s remove() Method Example

    Let us now see the example showing how to use set’s remove() method in Python.

    Example

    # python program to show the use of set remove() method  
    
      
    
    # creating a set  
    
    country_set = {'Pakistan', 'Brazil', 'Japan', 'China', 'USA'}  
    
    # printing the set  
    
    print("Given Set:", country_set)  
    
      
    
    # using the remove() method  
    
    country_set.remove('China')  
    
      
    
    # printing the updated set  
    
    print("Updated Set:", country_set)

    Output:

    Given Set: {'Brazil', 'China', 'Pakistan', 'Japan', 'USA'}
    Updated Set: {'Brazil', 'Pakistan', 'Japan', 'USA'}
    

    Explanation:

    In the above example, we have used the remove() method to remove the specified element from the given set.

    6) pop()

    Python set pop() method allows us to remove any random element from the set. This method returns the removed element.

    Syntax:

    The syntax of the pop() method is shown below:

    set_name.pop()  

    Python Set’s pop() Method Example

    We will now look at a simple example showing the implementation of set’s pop() method in Python.

    Example

    # python program to show the use of set pop() method  
    
      
    
    # creating a set  
    
    state_set = {'New York', 'Delhi', 'Tokyo', 'Penang', 'Ontario'}  
    
    # printing the set  
    
    print("Given Set:", state_set)  
    
      
    
    # using the pop() method  
    
    popped_item = state_set.pop()  
    
      
    
    # printing the updated set  
    
    print("Updated Set:", state_set)  
    
    print("Popped Element:", popped_item)

    Output:

    Given Set: {'Penang', 'Ontario', 'Tokyo', 'New York', 'Delhi'}
    Updated Set: {'Ontario', 'Tokyo', 'New York', 'Delhi'}
    Popped Element: Penang
    

    Explanation:

    In the above example, we have used the pop() method to remove and return a random element from the given set.

    7) update()

    Python set update() method is used to add elements from another set, list, tuple, or any other iterable to the set. Since sets are collections of unique elements, the update() method will only add the unique elements from the specified iterable to the targeted set.

    Syntax:

    The following is the syntax of the update() method:

    set_name.update(*others)  

    Python Set’s update() Method Example

    We will now look at a simple example showing the use case of set’s update() method in Python.

    Example

    # python program to show the use of set update() method  
    
      
    
    # given sets  
    
    num_set_1 = {4, 7, 8, 11, 19}  
    
    num_set_2 = {2, 5, 7, 8, 10}  
    
    print("Set 1:", num_set_1)  
    
    print("Set 2:", num_set_2)  
    
      
    
    # using the update() method  
    
    num_set_1.update(num_set_2)  
    
      
    
    # printing the updated set  
    
    print("Updated Set:", num_set_1)

    Output:

    Set 1: {19, 4, 7, 8, 11}
    Set 2: {2, 5, 7, 8, 10}
    Updated Set: {2, 4, 5, 7, 8, 10, 11, 19}
    

    Explanation:

    Here, we have used the update() method to add the elements from the second set to the first set. As a result, only the unique elements are added to the set.

    Set Operation Methods in Python

    In order to perform set operations like union, intersection, difference, and symmetric difference, there are various set methods available in Python.

    These methods to perform set operations are as follows:

    MethodDescription
    union()This method is utilized to return a set with elements from the set and all others.
    intersection()This method is utilized to return a set with common elements.
    difference()This method returns elements only in the set but not in others.
    symmetric_difference()This method returns elements in either set but not both.
    intersection_update()This method allows us to update the set with intersection.
    difference_update()This method is used to update the set with differences.
    symmetric_difference_update()This method updates the set with symmetric differences.
    issubset()This method allows us to check if the set is a subset.
    issuperset()This method is used to check if the set is a superset.
    isdisjoint()This method checks if sets have no elements in common.

    Let us see an example showing the use of some commonly used methods to perform set operations in Python.

    Example

    # simple python program to see the use of set operation methods  
    
      
    
    # given sets  
    
    set_A = {3, 6, 7, 9, 12}  
    
    set_B = {1, 2, 6, 7, 10}  
    
    print("Set A:", set_A)  
    
    print("Set B:", set_B)  
    
    print()  
    
    # union  
    
    union_set = set_A.union(set_B)  
    
    print("Union:", union_set)  
    
      
    
    # intersection  
    
    inters_set = set_A.intersection(set_B)  
    
    print("Intersection:", inters_set)  
    
      
    
    # difference  
    
    diff_set = set_A.difference(set_B)  
    
    print("Difference (set_A - set_B):", diff_set)  
    
      
    
    # symmetric difference  
    
    sym_diff_set = set_A.symmetric_difference(set_B)  
    
    print("Symmetric Difference:", sym_diff_set)

    Output:

    Set A: {3, 6, 7, 9, 12}
    Set B: {1, 2, 6, 7, 10}
    
    Union: {1, 2, 3, 6, 7, 9, 10, 12}
    Intersection: {6, 7}
    Difference (set_A - set_B): {9, 3, 12}
    Symmetric Difference: {1, 2, 3, 9, 10, 12}
    

    Explanation:

    In this example, we have performed set operations like union, intersection, difference, and symmetric difference using the set methods that Python offered us.

  • Python Sets

    In Python, a Set is one of the four built-in data types used to store numerous items in a single variable. Set is an unindexed and unordered collection of unique elements. For example, a set is suitable option when storing information about employee IDs as these IDs cannot have duplicates.

    Python Set

    Let us take a look at a simple example of a set.

    Example

    # creating a Set      
    
    S = {202, 205, 204, 209, 207}  
    
      
    
    print(S)

    Output:

    {209, 202, 204, 205, 207}

    Explanation:

    In the above example, we have created a simple set consisting of multiple items. Here, we can see that the items in the initialized set are unordered.

    A set is a mutable data type, meaning we can remove or add data elements to it. Python Sets are similar to the sets in mathematics, where we can perform operations like intersection, union, symmetric difference, and more.

    Characteristics of Python Sets

    Set in Python is a data type, which is:

    • Unordered: Sets do not maintain the order of how elements are stored in them.
    • Unindexed: We cannot access the data elements of sets.
    • No Duplicate Elements: Each data element in a set is unique.
    • Mutable (Changeable): Sets in Python allow modification of their elements after creation.

    Creating a Set

    Creating a set in Python is quite simple and easy process. Python offers two ways to create a set:

    1. Using curly braces
    2. Using set() function

    Using Curly Braces

    A set can be created by enclosing elements within curly braces ‘{}’, separated by commas.

    Let us see a simple example showing the way of creating a set using curly braces.

    Example

    # simple example to create a set using curly braces  
    
      
    
    int_set = {12, 6, 7, 9, 11, 10}   # set of integers  
    
    print(int_set)  
    
      
    
    str_set = {'one', 'two', 'three', 'four', 'five'} # set of strings  
    
    print(str_set)  
    
      
    
    mixed_set = {12, 'pythonapp', 7.2, 6e2} # mixed set  
    
    print(mixed_set)

    Output:

    {6, 7, 9, 10, 11, 12}
    {'one', 'three', 'two', 'four', 'five'}
    {600.0, 'pythonapp', 12, 7.2}
    

    Explanation:

    In this example, we have used the curly braces to create different types of sets. Moreover, we can observe that a set can store any number of items of different types, like integer, float, tuple, string, etc. However, a set cannot store mutable elements like lists, sets, or dictionaries.

    Using the set() Function

    Python offers an alternative way of creating a set with the help of its built-in function called set(). This function allow us to create a set from a passed iterable.

    The following example shows the way of using the set() function:

    Example

    # simple example to create a set using set() function  
    
      
    
    # given list  
    
    int_list = [6, 8, 1, 3, 7, 10, 4]  
    
      
    
    # creating set using set() function  
    
    int_set = set(int_list)  
    
      
    
    print("Set 1:", int_set)  
    
      
    
    # creating an empty set  
    
    empty_set = set()  
    
      
    
    print("Set 2:", empty_set)

    Output:

    Set 1: {1, 3, 4, 6, 7, 8, 10}
    Set 2: set()

    Explanation:

    In the above example, we have used the set() function to create set from a given list. We have also created an empty set by using the set() function without any arguments.

    Note: Creating an empty set is a bit tricky. Empty curly braces ‘{}’ will make an empty dictionary in Python.

    Accessing Elements of a Set

    Since sets are unordered and unindexed, we cannot access the elements by position. However, we can iterate through a set with the help of loops.

    Python Example to Access Element of a Set

    Let us see a simple example showing the way of iterating through a set in Python.

    Example

    # simple example to show how to iterate through a set  
    
      
    
    # given set  
    
    set_one = {11, 17, 12, 5, 7, 8}  
    
    print("Given Set:", set_one)  
    
      
    
    # iterating through the set using for loop  
    
    print("Iterating through the Set:")  
    
    for num in set_one:  
    
      print(num)

    Output:

    Given Set: {17, 5, 7, 8, 11, 12}
    Iterating through the Set:
    17
    5
    7
    8
    11
    12
    

    Explanation:

    In this example, we have used the ‘for’ loop to iterate through the elements of the given set.

    Adding Elements to the Set

    Python provides methods like add() and update() to add elements to a set.

    • add(): This method is used to add a single element to the set.
    • update(): This method is used to add multiple elements to the set.

    Python Set Example to Add Elements

    Let us see a simple example showing the way of adding elements to the set in Python.

    Example

    # simple example to show how to add elements to the set  
    
      
    
    # given set  
    
    subjects = {'physics', 'biology', 'chemistry'}  
    
    print("Given Set:", subjects)  
    
      
    
    # adding a single element to the set  
    
    subjects.add('maths')       # using add()  
    
    print("Updated Set (Added single element):", subjects)  
    
      
    
    # adding multiple elements to the set  
    
    subjects.update(['computer', 'english'])      # using update()  
    
    print("Update Set (Added Multiple elements):", subjects)

    Output:

    Given Set: {'physics', 'biology', 'chemistry'}
    Updated Set (Added single element): {'physics', 'biology', 'chemistry', 'maths'}
    Update Set (Added Multiple elements): {'physics', 'chemistry', 'english', 'biology', 'computer', 'maths'}
    

    Explanation:

    In this example, we have given a set consisting of 3 elements. We have then used the add() method to add a new element to the set. We have also used the update() method to add multiple elements to the given set.

    Removing Elements from the Set

    In Python, we can easily remove elements from a given set using methods like remove(), discard(), pop(), and clear().

    • remove(): This method allow us to remove a specific element from the set. It will raise a KeyError if the element is not found in the given set.
    • discard(): This method is also used to remove a specified element from the set; however, it does not raise any error if the element is not found.
    • pop(): This method is used to remove and returns a random element from the set.
    • clear(): This method is used to remove all the elements from the given set.

    Python Example to Remove Elements from the Set

    Here is a simple example showing the working of these methods to remove elements from a set in Python.

    Example

    # simple example to show how to remove elements from the set  
    
      
    
    # given set  
    
    subjects = {'physics', 'chemistry', 'english', 'biology', 'computer', 'maths'}  
    
    print("Given Set:", subjects)  
    
      
    
    # removing a specified element from the set  
    
    subjects.remove('maths')      # using remove()  
    
    print("Updated Set (Removed 'maths'):", subjects)  
    
      
    
    # removing a specified element from the set  
    
    subjects.discard('chemistry')      # using discard()  
    
    print("Updated Set (Removed 'chemistry'):", subjects)  
    
      
    
    # removing a random element from the set  
    
    subjects.pop()      # using pop()  
    
    print("Updated Set (Removed a random element'):", subjects)  
    
      
    
    # removing all elements from the set  
    
    subjects.clear()      # using clear()  
    
    print("Updated Set (Removed all elements):", subjects)

    Output:

    Given Set: {'physics', 'chemistry', 'english', 'computer', 'biology', 'maths'}
    Updated Set (Removed 'maths'): {'physics', 'chemistry', 'english', 'computer', 'biology'}
    Updated Set (Removed 'chemistry'): {'physics', 'english', 'computer', 'biology'}
    Updated Set (Removed a random element'): {'english', 'computer', 'biology'}
    Updated Set (Removed all elements): set()
    

    Explanation:

    In this example, we have given a set consisting of six elements. We have then used the remove(), and discard() methods to remove the specified elements from the set. We have then used the pop() method to remove a random element from the set. At last, we have used the clear() method to remove all the elements from the given set. As a result, the set becomes empty.

    Set Operations in Python

    Similar to the Set Theory in Maths, Python sets also provide support to various mathematical operations like union, intersection, difference, symmetric difference and more.

    Let us discuss some of these operations with the help of examples.

    Union of Sets

    In mathematical terms, union of sets A and B is defined as the set of all those elements which belongs to A or B or both and is denoted by A∪B.

    A∪B = {x: x ∈ A or x ∈ B}  
    Python Set

    For instance, let A = {1, 2, 3}, and B = {2, 3, 4, 5}. Therefore, A∪B = {1, 2, 3, 4, 5}.

    Similarly in Python, we can perform union of sets by combining their elements, and eliminating duplicates with the help of the | operator or union() method.

    Python Example for Union of Sets

    Let us see a simple example showing the union of sets in Python.

    Example

    # simple example on union of sets  
    
      
    
    set_A = {1, 2, 3}     # set A  
    
    print("Set A:", set_A)  
    
      
    
    set_B = {2, 3, 4, 5}  # set B  
    
    print("Set B:", set_B)  
    
          
    
    print("\nUnion of Sets A and B:")       # union of sets  
    
    print("Method 1:", set_A | set_B)       # using |  
    
    print("Method 2:", set_A.union(set_B))  # using union()

    Output:

    Set A: {1, 2, 3}
    Set B: {2, 3, 4, 5}
    
    Union of Sets A and B:
    Method 1: {1, 2, 3, 4, 5}
    Method 2: {1, 2, 3, 4, 5}
    

    Explanation:

    In the above example, we have defined two sets and performed their union using the | operator and union() method.

    Intersection of Sets

    In mathematical terms, intersection of two sets A and B is defined as the set of all those elements which belongs to both A and B and is denoted by A∩B.

    A∩B = {x: x ∈ A and x ∈ B}  
    Python Set

    For instance, let A = {1, 2, 3}, and B = {2, 3, 4, 5}. Therefore, A∩B = {2, 3}.

    Similarly in Python, we can perform intersection of sets by using the & operator or intersection() method to return the elements common in both sets.

    Example of Set Intersection in Python

    Let us see a simple example showing the intersection of sets in Python.

    Example

    # simple example on intersection of sets  
    
      
    
    set_A = {1, 2, 3}     # set A  
    
    print("Set A:", set_A)  
    
      
    
    set_B = {2, 3, 4, 5}  # set B  
    
    print("Set B:", set_B)  
    
      
    
    print("\nIntersection of Sets A and B:")       # intersection of sets  
    
    print("Method 1:", set_A & set_B)       # using &  
    
    print("Method 2:", set_A.intersection(set_B))  # using intersection()

    Output:

    Set A: {1, 2, 3}
    Set B: {2, 3, 4, 5}
    
    Intersection of Sets A and B:
    Method 1: {2, 3}
    Method 2: {2, 3}
    

    Explanation:

    In the above example, we have defined two sets and performed their intersection using the & operator and intersection() method.

    Difference of Sets

    In mathematical terms, difference of two sets A and B is defined as the set of all those elements which belongs to A, but do not belong to B and is denoted by A-B.

    A-B = {x: x ∈ A and x ∉ B}  
    Python Set

    For instance, let A = {1, 2, 3}, and B = {2, 3, 4, 5}. Therefore, A-B = {1} and B-A = {4, 5}.

    Similarly in Python, we can perform difference of sets by using the – operator or difference() method to return the elements present in the first set but not in the second one.

    Python Example to Show the Difference of Sets

    Let us see a simple example showing the difference of sets in Python.

    Example

    # simple example on difference of sets  
    
      
    
    set_A = {1, 2, 3}     # set A  
    
    print("Set A:", set_A)  
    
      
    
    set_B = {2, 3, 4, 5}  # set B  
    
    print("Set B:", set_B)  
    
      
    
    print("\nA - B:")       # difference of sets  
    
    print("Method 1:", set_A - set_B)       # using -  
    
    print("Method 2:", set_A.difference(set_B))  # using difference()  
    
      
    
    print("\nB - A:")  
    
    print("Method 1:", set_B - set_A)       # using -  
    
    print("Method 2:", set_B.difference(set_A))  # using difference()

    Output:

    Set A: {1, 2, 3}
    Set B: {2, 3, 4, 5}
    
    A - B:
    Method 1: {1}
    Method 2: {1}
    
    B - A:
    Method 1: {4, 5}
    Method 2: {4, 5}
    

    Explanation:

    In the above example, we have defined two sets and performed their difference using the – operator and difference() method.

    Set Comprehension

    In Python, set comprehension allows us to create sets in a concise and easy way.

    The following example demonstrates how set comprehension works in Python:

    Example

    # simple example on set comprehension  
    
      
    
    # creating a set of square of numbers  
    
    set_of_squares = {i**2 for i in range(6)}  
    
    print(set_of_squares)  
    
      
    
    # creating a set of cube of numbers  
    
    set_of_cubes = {i**3 for i in range(6)}  
    
    print(set_of_cubes)

    Output:

    {0, 1, 4, 9, 16, 25}
    {0, 1, 64, 8, 27, 125}
    

    Explanation:

    In the above example, we have used the set comprehension to create the desired set.

    Frozenset in Python

    A frozenset is an immutable version of a set, meaning we cannot add or remove elements from it once created. We can create a frozeset object using Python’s built-in function called frozenset().

    Python Frozenset Example

    Let us see a simple example showing how to create a frozenset in Python.

    Example

    # simple example to create a frozenset  
    
      
    
    # using the frozenset() function  
    
    imm_set = frozenset(['one', 'two', 'three', 'four', 'five'])  
    
      
    
    # printing results  
    
    print(imm_set)  
    
    print(type(imm_set))  # returning type

    Output:

    frozenset({'two', 'one', 'five', 'four', 'three'})
    <class 'frozenset'>

    Explanation:

    In the above example, we have used the frozenset() function to return the frozenset object of the passed iterable. Frozensets are hashable objects that can be used as keys in dictionaries or elements of other sets.

    Conclusion

    Python sets are a powerful tool to handle collections of unique items. Sets in Python provides efficient operations to test membership, eliminate duplicates, and perform mathematical set operations. Understanding sets and their capabilities can greatly boost the skills to handle data and develop algorithm in Python.

  • Difference between List and Tuple in Python

    List and Tuple have various features and advantages in common, they have significant differences and distinct features that affect their usage, such as mutability, performance, and memory usage. Lists are mutable, which enables us to add, delete, or modify the elements.

    The Tuples are immutable, which do not allow modifications or changes. Choosing an appropriate data type between them depends on our needs, whether we want to modify the data or prioritize performance and memory efficiency.

    What is a List?

    In Python, A List is an ordered, mutable collection of elements. It allows us to perform various modifications such as adding, removing, or changing elements.

    Characteristics of Lists:

    Here are some of the important features of Python lists:

    Difference between List and Tuple in Python
    • Ordered: In this, A List maintains a particular order of its elements with an index starting from 0.
    • Mutable: In the Mutable data type, we can edit or make changes to the elements.
    • Dynamic:The List can grow or shrink in size dynamically.
    • Supports Multiple Data Types:A list can contain elements of various and distinct data types.
    • The List uses square brackets ([]) for declaration.

    Python List Example

    Let us look at an example to create a list in Python.

    Example

    # creating a list  
    
    tst_lst = [19, 23, 10, "pythonapp", 7.8]  
    
      
    
    # printing the list  
    
    print("Initialized list:", tst_lst)  
    
    print("Data Type:", type(tst_lst))

    Output:

    Initialized list: [19, 23, 10, 'pythonapp', 7.8]
    Data Type: <class 'list'>

    Explanation:

    In the above example, we have created a list using square brackets [] and printed it. We can observe that the initialized list consists of different data types like integer, string, and float.

    What is a Tuple?

    A tuple is an ordered, immutable collection of elements, which means that once created, its elements cannot be changed.

    Characteristics of Tuples:

    Here are some of the features included in Python Tuples:

    Difference between List and Tuple in Python
    • Ordered: Like lists, in a Tuple, elements have a specific order and can be accessed via an index.
    • Immutable: In the Immutable data type, we cannot edit or make changes to the elements.
    • Faster than lists: Since tuples are immutable, Python optimizes their storage and processing.
    • Supports Multiple Data Types: A tuple can consist of elements of different types.
    • Tuples use parentheses (()) for declaration.

    Python Tuple Example

    Let us look at an example to create a tuple in Python.

    Example

    # creating a tuple  
    
    tst_tpl = (19, 23, 10, "pythonapp", 7.8)  
    
      
    
    # printing the tuple  
    
    print("Initialized Tuple:", tst_tpl)  
    
    print("Data Type:", type(tst_tpl))

    Output:

    Initialized Tuple: (19, 23, 10, 'pythonapp', 7.8)
    Data Type: <class 'tuple'>
    

    Explanation:

    In the above example, we have created a list using parentheses () and printed it. We can observe that the initialized tuple consists of different data types like integer, string, and float. We have printed the data, which is the tuple.

    Key Differences between Lists and Tuples

    The following are key differences between Lists and Tuples in Python:

    FeatureListTuple
    MutabilityWe can modify a list by adding or removing items (Mutable).We cannot modify a tuple by adding or removing items (Immutable).
    PerformanceLists are slower due to mutability.Tuples are faster due to their static size and immutability.
    Memory UsageList uses more memory.Tuple uses less memory.
    MethodsPython List offers more built-in methods. (e.g., append, extend, remove)Python Tuple offers fewer built-in methods. (e.g., index, count)
    SyntaxWe can define a list using square brackets [].We can define a tuple using parentheses ().
    Iteration SpeedIteration is slightly slower in Lists due to their dynamic nature.Iteration is faster in Tuples as they are immutable.
    Storage EfficiencyLists require extra memory for dynamic allocation.Tuples are more memory-efficient
    Error SafetyLists are prone to accidental changes.Tuples provide data integrity to prevent errors.
    Use CaseLists are used when data needs to change.Tuples are used when data should remain constant.
    Examplesample_list = [12, 1, 5, 8, 4]sample_tuple = (12, 1, 5, 8, 4)

    Mutability Test: Lists vs Tuples

    The main difference between List and Tuple is mutability. A list is a mutable data type, meaning that its elements can be changed, added, or removed after initialization.

    On the other hand, a Tuple is an immutable data type that cannot be changed after initialization. Any attempt to change an item will result in an error.

    Example

    # Modifying a list  
    
    tst_lst = [14, 23, 39]  
    
    print("Given List:", tst_lst)  
    
    tst_lst[0] = 17  
    
    print("Modified List:", tst_lst)  
    
      
    
    print()  
    
    # Modifying a tuple (Raises an error)  
    
    tst_tpl = (14, 23, 39)  
    
    print("Given Tuple:", tst_tpl)  
    
    tst_tpl[0] = 17  # TypeError: 'tuple' object does not support item assignment

    Output:

    Given List: [14, 23, 39]
    Modified List: [17, 23, 39]
    
    Given Tuple: (14, 23, 39)
    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    <file-name> n <cell line: 0>()
    9 tst_tpl = (14, 23, 39)
    10 print("Given Tuple:", tst_tpl)
    ---> 11 tst_tpl[0] = 17 # TypeError: 'tuple' object does not support item assignment
    
    TypeError: 'tuple' object does not support item assignment
    

    Explanation:

    In the above example, we have initialized a list and used indexing to modify its element. As a result, the list is modified successfully. Whereas, in the case of tuples, we have initialized one, but we can observe a returned error when we try modifying it.

    Performance and Memory Comparison: Lists vs Tuples

    Tuples are generally more memory-efficient and faster than lists. This is because:

    • Lists require additional memory allocation for dynamic resizing.
    • Tuples are stored in a more optimized way due to their immutability.

    Example

    import sys  
    
      
    
    tst_lst = [19, 24, 3, 54, 25]  
    
    tst_tpl = (19, 24, 3, 54, 25)  
    
      
    
    print(sys.getsizeof(tst_lst))  # More memory usage  
    
    print(sys.getsizeof(tst_tpl))  # Less memory usage

    Output:

    104
    80
    

    Explanation:

    In the above example, we have imported the sys module and initialized a list and a tuple. We have then used the getsizeof() function to return the size of the list and the tuple. As a result, we can observe that the list takes more memory than a tuple.

    When to Use Lists?

    We can use a list when data needs to be modified dynamically, such as adding/removing elements. The list can be used when we need a sequence with flexible operations. We can use a list while working with large datasets that require updates periodically.

    When to Use Tuples?

    Tuples are used when data should remain unchanged (e.g., database records, configuration settings). Tuples can be used when performance is the most important factor and critical because tuples are faster and use less memory. Tuples can also be used as dictionary keys, as tuples are hashable, but lists are not.

    Conclusion

    We have studied a lot about the differences between lists and Tuples. A list is an ordered, mutable collection of elements. It allows us to perform various modifications such as adding, removing, or changing elements, whereas a tuple is an ordered but immutable collection of elements, which means that once created, its elements cannot be changed.

    We also learnt about the differences between Lists and tuples with the help of the table, which helped us in recapping the differences in short.

  • Python Tuple Methods

    In Python, Tuple methods are built-in functions that we can use to perform different operations on tuples. These methods provides a convenient way for manipulating and analyzing tuple data.

    Since tuple is an immutable collection of elements, there are only a few built-in methods available for us to work with. Unlike lists, we cannot add, remove, or sort elements in a tuple once it’s created.

    The only two built-in methods that tuples support are:

    1. count()
    2. index()

    We are now going to discuss these methods with the help of examples:

    Tuple count() Method

    The count() method is a built-in Python method that allow us to count the occurrence of the specified element in a tuple. This method takes a single argument as the element to be counted and returns its occurrence in the given tuple.

    Python Tuple Methods

    Syntax:

    The syntax of the count() method is shown below:

    tuple_name.count(item)  

    Parameter:

    • item (required):The item parameter is the element to be searched in the tuple.

    Return:

    • The number of times the specified item appeared in the tuple.

    Python Tuple count() Method Example

    We are now going to look at a simple example showing the use of the tuple’s count() method in Python.

    Example

    # simple python program to show the use of the count() method  
    
      
    
    # given tuples  
    
    tuple_of_numbers = (1, 3, 4, 5, 2, 4, 6)  
    
    tuple_of_countries = ('Pakistan', 'USA', 'France', 'USA',   
    
                          'Germany', 'Pakistan', 'Pakistan', 'Brazil', 'Japan')  
    
      
    
    print("Tuple 1:", tuple_of_numbers)  
    
    # counting the occurrence of 4  
    
    count_of_4 = tuple_of_numbers.count(4)  
    
    print("Count of 4:", count_of_4)  
    
      
    
    print() # empty line  
    
    print("Tuple 2:", tuple_of_countries)  
    
    # counting the occurrence of 'Pakistan'  
    
    Pakistan = tuple_of_countries.count('Pakistan')  
    
    print("Count of Pakistan:", Pakistan)

    Output:

    Tuple 1: (1, 3, 4, 5, 2, 4, 6)
    Count of 4: 2
    
    Tuple 2: ('Pakistan', 'USA', 'France', 'USA', 'Germany', 'Pakistan', 'Pakistan', 'Brazil', 'Japan')
    Count of Pakistan: 3
    

    Explanation:

    Here, we have used the count() method to find the total occurrences of the specified elements in the given tuples.

    Python Example to count nested tuples and lists in Tuples

    Let us now see another example showing the way of counting nested tuples and lists in Tuples.

    Example

    # python example to count nested tuples and lists  
    
      
    
    # given tuple  
    
    given_tuple = ((4, 5), 1, (4, 5), [4, 5], (2, ), 4, 5)  
    
    print("Given Tuple:", given_tuple)  
    
      
    
    # counting the tuple (4, 5) in given tuple  
    
    tpl_1 = given_tuple.count((4, 5))  
    
    print("Count of (4, 5):", tpl_1)  
    
      
    
    # counting the list [4, 5] in given tuple  
    
    lst_1 = given_tuple.count([4, 5])  
    
    print("Count of [4, 5]:", lst_1)

    Output:

    Given Tuple: ((4, 5), 1, (4, 5), [4, 5], (2,), 4, 5)
    Count of (4, 5): 2
    Count of [4, 5]: 1
    

    Explanation:

    Here, we have used the count() method to find the total occurrence of the specified tuple and list in the given tuple.

    Tuple index() Method

    The index() method is a built-in Python method allows us to search for a specified element in the tuple and return its position. We can also select an optional range in order to search a particular region in the tuple.

    Python Tuple Methods

    Syntax:

    The syntax of the index() method is shown below:

    tuple_name.index(item[, start[, stop]])  

    Parameter:

    • item (required): The item parameter is the element to be searched in the tuple.
    • start (optional): The start parameter specifies the starting index for the search.
    • end (optional): The end parameter specifies the ending index.

    Return:

    • An Integer Value indicating the index of the first occurrence of the specified value.

    Note: This method is raise a ValueError exception if the specified element is not found in the tuple.

    Python Tuple index() method Example

    We are now going to see a simple example to understand the working of the tuple’s index() method in Python.

    Example

    # simple python program to show the use of the index() method  
    
      
    
    # given tuple  
    
    tuple_of_fruits = ('orange', 'apple', 'banana', 'mango',   
    
                       'apple', 'melon', 'cherries', 'grapes')  
    
    print("Given Tuple:", tuple_of_fruits)  
    
      
    
    # getting the index of 'apple'  
    
    idx_of_apple = tuple_of_fruits.index('apple')  
    
    print("First occurrence of 'apple':", idx_of_apple)  
    
      
    
    # getting the index of 'apple' after 3rd index  
    
    idx_of_apple = tuple_of_fruits.index('apple', 3)  
    
    print("First occurrence of 'apple' after 3rd index:", idx_of_apple)

    Output:

    Given Tuple: ('orange', 'apple', 'banana', 'mango', 'apple', 'melon', 'cherries', 'grapes')
    First occurrence of 'apple': 1
    First occurrence of 'apple' after 3rd index: 4
    

    Explanation:

    Here, we have used the index() method to find the first appearance of the specified elements in the given tuple.

    Python Tuple index() Method Example Without Any Element

    Let us see an example showing what will happen if the element does not exist in the given tuple.

    Example

    # example to find element that is not found in the tuple  
    
      
    
    # given tuple  
    
    tpl_1 = (1, 3, 4, 5, 6, 2, 7, 4, 9, 1)  
    
      
    
    # getting the index of 8  
    
    idx_of_8 = tpl_1.index(8)

    Output:

    ValueError: tuple.index(x): x not in tuple

    Explanation:

    Here, we can observe that the index() method has raised the ValueError exception as the specified element is not found in the given tuple.

    Python Tuple Methods FAQs

    1. Do tuples have methods in Python?

    Yes, Python tuples have two built-in methods:

    • count(): This method is used to return the number of times the specified element appears in the tuple.
    • index(): This method is used to return the first index of the specified element in the tuple. It raises a ValueError exception if the element is not found.

    2. Why are there only a few methods available for tuples?

    Tuple is an immutable data type, meaning we cannot change its content once created. Most list methods, like append() or remove(), modify data, so they are not available for tuples.

    3. Can we add or remove items from a tuple?

    No, we cannot directly add or remove elements from a tuple because it is immutable. However, we can create a new tuple by combining the existing ones, as shown in the following example:

    Example

    # given tuple  
    
    tpl_1 = (1, 3, 5, 2)  
    
      
    
    # creating a new tuple  
    
    tpl_2 = tpl_1 + (4,)  
    
    print(tpl_2)

    Output:

    (1, 3, 5, 2, 4)

    4. How to convert a tuple to a list to modify it?

    We can make use of the list() function to convert a given tuple to a list, make changes, and then convert it back.

    Here is an example showing the way of converting a tuple to a list:

    Example

    # given tuple  
    
    tpl_1 = (1, 3, 5, 2)  
    
      
    
    # converting tuple to a list  
    
    lst_1 = list(tpl_1)  
    
    lst_1.append(4) # making changes  
    
      
    
    # converting list back to a tuple  
    
    tpl_1 = tuple(lst_1)  
    
    print(tpl_1)

    Output:

    (1, 3, 5, 2, 4)

    5. Can we store mutable elements like lists inside a tuple?

    Yes, but we need to be cautious while storing mutable elements like lists inside a tuple. The tuple itself remains immutable; however, we can change the mutable elements like the list inside it.

    Let us see an example:

    Example

    # given tuple  
    
    tpl_1 = ([1, 3], 5)  
    
      
    
    # changing list inside the tuple  
    
    tpl_1[0].append(2)  
    
    print(tpl_1)

    Output:

    ([1, 3, 2], 5)
  • Python Tuples

    Tuple is a built-in data structure in Python for storing a collection of objects. A tuple is quite similar to a Python list in terms of indexing, nested objects, and repetition; however, the main difference between both is that the tuples in Python are immutable, unlike the Python list which is mutable.

    Let us see a simple example of initializing a tuple in Python.

    Example

    # creating a tuple  
    
    T = (20, 'Learn Python', 35.75, [20, 40, 60])  
    
      
    
    print(T)

    Output:

    (20, 'Learn Python', 35.75, [20, 40, 60])

    Explanation:

    In the above example, we have created a simple tuple consisting of multiple elements of different data types. Each element in this tuple is indexed, meaning it can be accessed using its position in the list, as shown below:

    • T[0] = 20 (Integer)
    • T[1] = ‘TpointTech’ (String)
    • T[2] = 35.75 (Float)
    • T[3] = [20, 40, 60] (Nested List)

    Characteristics of Python Tuples

    Tuple in Python is a data structure, which is

    • Ordered: Each data element in a tuple has a particular order that never changes.
    • Immutable: The data elements of tuple cannot be changed once initialized.

    Let us take a look at the following example showing that Tuples are immutable.

    Example

    # creating a tuple    
    
    my_tpl = (25, 16.25, 'Learn Python', [20, 40, 60], 3e8)    
    
    print(my_tpl)  
    
      
    
    # trying to changing the element of the tuple    
    
    # my_tpl[1] = 'welcome' # raise TypeError

    Output:

    (25, 16.25, 'Learn Python', [20, 40, 60], 300000000.0)

    Creating a Tuple

    All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.

    Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.

    Let us consider the following example demonstrating the inclusion of different data types in a tuple:

    Example

    # Python program to show how to create a tuple  
    
      
    
    # Creating an empty tuple      
    
    empty_tpl = ()      
    
    print("Empty tuple: ", empty_tpl)      
    
          
    
    # Creating a tuple having integers      
    
    int_tpl = (13, 56, 27, 18, 11, 23)  
    
    print("Tuple with integers: ", int_tpl)      
    
          
    
    # Creating a tuple having objects of different data types  
    
    mix_tpl = (6, "Tpointtech", 17.43)      
    
    print("Tuple with different data types: ", mix_tpl)      
    
          
    
    # Creating a nested tuple      
    
    nstd_tpl = ("Tpointtech", {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))      
    
    print("A nested tuple: ", nstd_tpl)

    Output:

    Empty tuple: ()
    Tuple with integers: (13, 56, 27, 18, 11, 23)
    Tuple with different data types: (6, 'Tpointtech', 17.43)
    A nested tuple: ('Tpointtech', {4: 5, 6: 2, 8: 2}, (5, 3, 15, 6))
    

    Explanation:

    In the above snippet of code, we have created four different tuples containing different types of elements. The first tuple is an empty tuple defined using the parentheses with no element in between. After that, we have defined an integer tuple consisting of 6 integer values between the parentheses separated by the commas. The third tuple is comprised of three objects of different data types – integer, string, and float. At last, we have defined a tuple as a different object, including another tuple.

    Accessing Tuple Elements

    In Python, we can access any object of a tuple using indices. The objects or elements of a tuple can be accessed by referring to the index number, inside of square brackets ‘[]’.

    Let us consider the following example illustrating how to access an element of a tuple using indexing:

    Example

    # Python program to show how to access tuple elements      
    
      
    
    # Creating a tuple having six elements  
    
    sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")   
    
      
    
    # accessing the elements of a tuple using indexing  
    
    print("sampleTuple[0] =", sampleTuple[0])  
    
    print("sampleTuple[1] =", sampleTuple[1])  
    
    print("sampleTuple[-1] =", sampleTuple[-1])   # negative indexing  
    
    print("sampleTuple[-2] =", sampleTuple[-2])

    Output:

    sampleTuple[0] = Apple
    sampleTuple[1] = Mango
    sampleTuple[-1] = Berries
    sampleTuple[-2] = Guava
    

    Explanation:

    In the above example, we have created a tuple consisting of six elements. We have then used the indexing to access the different elements of the tuple.

    Slicing in Tuple

    Slicing a tuple means dividing a tuple into smaller tuples with the help of indexing. In order to slice a tuple, we need to specify the starting and ending index value, that will return a new tuple with the specified objects.

    We can slice a tuple using the colon ‘:’ operator separating the start and end index as shown below:

    Syntax:

    It has the following syntax:

    tuple[start:end]  

    Python Tuple Slicing Example

    Let us consider a simple example showing the way of slicing a tuple in Python.

    Example

    # Python program to show how slicing works in Python tuples  
    
      
    
    # Creating a tuple  
    
    sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")  
    
      
    
    # Using slicing to access elements of the tuple  
    
    print("Elements between indices 1 and 5: ", sampleTuple[1:5])  
    
      
    
    # Using negative indexing in slicing  
    
    print("Elements between indices 0 and -3: ", sampleTuple[:-3])  
    
      
    
    # Printing the entire tuple by using the default start and end values  
    
    print("Entire tuple: ", sampleTuple[:])

    Output:

    Elements between indices 1 and 5: ('Mango', 'Banana', 'Orange', 'Guava')
    Elements between indices 0 and -3: ('Apple', 'Mango', 'Banana')
    Entire tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
    

    Explanation:

    In this example, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have printed the tuple of elements ranging from 1 to 5 using the slicing method. We have then printed the elements ranging from 0 to -3 using the negative indexing in slicing. At last, we have printed the entire tuple using the colon ‘:’ operator only without specifying the start and end index values.

    Deleting a Tuple

    Unlike lists, tuples are immutable data types meaning that we cannot update the objects of a tuple once it is created. Therefore, removing the elements of the tuple is also not possible. However, we can delete the entire tuple using the ‘del’ keyword as shown below.

    Syntax:

    It has the following syntax:

    del tuple_name  

    Python Example to Delete a Tuple

    Let us consider the following snippet of code illustrating the method of deleting a tuple with the help of the ‘del’ keyword. Here is a simple example showing the way of deleting a tuple in Python.

    Example

    # Python program to show how to delete elements of a Python tuple  
    
      
    
    # Creating a tuple  
    
    sampleTuple = ("Apple", "Mango", "Banana", "Orange", "Guava", "Berries")  
    
    # printing the entire tuple for reference  
    
    print("Given Tuple:", sampleTuple)  
    
      
    
    # Deleting a particular element of the tuple using the del keyword  
    
    try:  
    
        del sampleTuple[3]  
    
        print(sampleTuple)  
    
    except Exception as e:  
    
        print(e)  
    
      
    
    # Deleting the variable from the global space of the program using the del keyword  
    
    del sampleTuple  
    
      
    
    # Trying accessing the tuple after deleting it  
    
    try:  
    
        print(sampleTuple)  
    
    except Exception as e:  
    
        print(e)

    Output:

    Given Tuple: ('Apple', 'Mango', 'Banana', 'Orange', 'Guava', 'Berries')
    'tuple' object doesn't support item deletion
    name 'sampleTuple' is not defined
    

    Explanation:

    Here, we have defined a tuple consisting of six elements – Apple, Mango, Banana, Orange, Guava, and Berries. We have then printed the entire tuple for reference. After that, we have used the try and except blocks to delete a particular element from the tuple using the del keyword. As a result, an exception has been raised saying ‘tuple’ object doesn’t support item deletion. We have then used the del keyword to delete the entire tuple and tried printing it. As a result, we can observe another exception saying name ‘sampleTuple’ is not defined.

    Changing the Elements in Tuple

    Once we create a tuple, it is impossible for us to change its elements due its immutable nature. However, there is a way to update the elements of a tuple. We can convert the tuple into a list, change the list, and convert the list back into a tuple.

    Python Example to Change the Element in Tuple

    Let us see a simple example showing the way of updating elements of a Tuple in Python.

    Example

    # Python program to demonstrate the approach of changing the element in the tuple  
    
      
    
    # creating a tuple  
    
    fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  
    
      
    
    # printing the tuple before update  
    
    print("Before Changing the Element in Tuple...")  
    
    print("Tuple =", fruits_tuple)  
    
      
    
    # converting the tuple into the list  
    
    fruits_list = list(fruits_tuple)  
    
      
    
    # changing the element of the list  
    
    fruits_list[2] = "grapes"  
    
    print("Converting", fruits_tuple[2], "=>", fruits_list[2])  
    
      
    
    # converting the list back into the tuple  
    
    fruits_tuple = tuple(fruits_list)  
    
      
    
    # printing the tuple after update  
    
    print("After Changing the Element in Tuple...")  
    
    print("Tuple =", fruits_tuple)

    Output:

    Before Changing the Element in Tuple...
    Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
    Converting banana => grapes
    After Changing the Element in Tuple...
    Tuple = ('mango', 'orange', 'grapes', 'apple', 'papaya')
    

    Explanation:

    In this example, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have converted the tuple into a list using the list() method. We have then changed the element at index 2 of the list to ‘grapes’ and used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element at index 2 also changed from ‘banana’ to ‘grapes’ respectively.

    Adding Elements to a Tuple

    Since Tuple is an immutable data type, it does not have the built-in append() method to add the elements. However, there are few ways we can use in order to add an element to a tuple.

    Converting the Tuple into a List

    In order to add a new element to a tuple, we can follow a similar approach we used while changing the element in a tuple. The approach follows the steps discussed below:

    Step 1: Convert the Tuple into a List.

    Step 2: Add the required element to the list using the append() method.

    Step 3: Convert the List back into the Tuple.

    Let us consider the following snippet of code, demonstrating the same.

    Example

    # Python program to demonstrate an approach of adding the element in the tuple by converting it into a list  
    
      
    
    # creating a tuple  
    
    fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  
    
      
    
    # printing the tuple before update  
    
    print("Before Adding a New Element in Tuple...")  
    
    print("Original Tuple =", fruits_tuple)  
    
      
    
    # converting the tuple into the list  
    
    fruits_list = list(fruits_tuple)  
    
      
    
    # changing the element of the list  
    
    fruits_list.append("blueberry")  
    
    print("Adding New Element -> 'blueberry'")  
    
      
    
    # converting the list back into the tuple  
    
    fruits_tuple = tuple(fruits_list)  
    
      
    
    # printing the tuple after update  
    
    print("After Adding a New Element in Tuple...")  
    
    print("Updated Tuple =", fruits_tuple)

    Output:

    Before Adding a New Element in Tuple...
    Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
    Adding New Element -> 'blueberry'
    After Adding a New Element in Tuple...
    Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'blueberry')
    

    Explanation:

    In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have convert the tuple into a list using the list() method. We have then added a new element ‘blueberry’ in the list using the append() method. After that, we have used the tuple() method to convert the update list back to the tuple. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘blueberry’ has been added to the given tuple respectively.

    Adding a Tuple to a Tuple

    In Python, we are allowed to add multiple tuples to tuples. Therefore, if we want to insert a new element to a tuple, we can follow the steps as shown below:

    Step 1: Create a new Tuple with the element(s) we want to add.

    Step 2: Adding the new tuple to the existing tuple.

    Let us consider the following example, illustrating the same.

    Example

    # Python program to demonstrate an approach of adding the element in the tuple by adding a new tuple to the existing one  
    
      
    
    # creating a tuple  
    
    fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  
    
      
    
    # printing the tuple before update  
    
    print("Before Adding a New Element in Tuple...")  
    
    print("Original Tuple =", fruits_tuple)  
    
      
    
    # creating a new tuple consisting new element(s)  
    
    temp_tuple = ("pineapple", )  
    
      
    
    # adding the new tuple to the existing tuple  
    
    # fruits_tuple = fruits_tuple + temp_tuple  
    
    fruits_tuple += temp_tuple  
    
      
    
    # printing the tuple after update  
    
    print("Adding New Element -> 'pineapple'")  
    
    print("After Adding a New Element in Tuple...")  
    
    print("Updated Tuple =", fruits_tuple)

    Output:

    Before Adding a New Element in Tuple...
    Original Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya')
    Adding New Element -> 'pineapple'
    After Adding a New Element in Tuple...
    Updated Tuple = ('mango', 'orange', 'banana', 'apple', 'papaya', 'pineapple')
    

    Explanation:

    In the above snippet of code, we have created a tuple consisting of five elements – mango, orange, banana, apple, and papaya. We have then printed the tuple for reference. After that, we have created a new tuple consisting of another element ‘blueberry’. After that, we have added the new tuple to the existing tuple using the ‘+’ operator. At last, we have printed the resultant tuple. As a result, we can observe that the tuple has been updated and the element ‘pineapple’ has been added to the given tuple respectively.

    Unpacking Tuples

    While initializing a tuple, we generally assign objects to it. This process is known as ‘packing’ a tuple. However, Python offers us an accessibility to extract the objects back into variables. This process of extracting the objects from a tuple and assign them to different variables is known as ‘unpacking’ a tuple.

    Python Example for Unpacking Tuples

    Let us consider the following example illustrating the way of unpacking a tuple in Python.

    Example

    # Python program to demonstrate an approach of unpacking a tuple  
    
      
    
    # creating a tuple (Packing a Tuple)  
    
    fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  
    
      
    
    # printing the given tuple for reference  
    
    print("Given Tuple :", fruits_tuple)  
    
      
    
    # unpacking a tuple  
    
    (varOne, varTwo, varThree, varFour, varFive) = fruits_tuple  
    
      
    
    # printing the results  
    
    print("First Variable :", varOne)  
    
    print("Second Variable :", varTwo)  
    
    print("Third Variable :", varThree)  
    
    print("Fourth Variable :", varFour)  
    
    print("Fifth Variable :", varFive)

    Output:

    Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
    First Variable : mango
    Second Variable : orange
    Third Variable : banana
    Fourth Variable : apple
    Fifth Variable : papaya
    

    Explanation:

    In the above snippet of code, we have created a tuple of five elements – mango, orange, banana, apple, and papaya. We have printed the initialized tuple for reference. After that, we have unpacked the tuple by assigning each element of the tuple at right to their corresponding variables at left. At last, we have printed the values of different initialized variables. As a result, the tuple is unpacked successfully, and the values are assigned to the variables.

    Note:While unpacking a tuple, the number of variables on left-hand side should be equal to the number of elements in a given tuple. In case, the variables do not match the size of the tuple, we can use an asterisk ‘*’ in order to store the remaining elements as a list.

    Looping Tuples

    Python offers different ways to loop through a tuple. Some of these ways are as follows:

    • Using ‘for’ loop
    • Using ‘while’ loop

    Python Looping Tuples Example

    Here is a simple example showing the ways of looping through a Tuple in Python

    Example

    # Python program to loop through a tuple  
    
      
    
    # creating a tuple  
    
    fruits_tuple = ("mango", "orange", "banana", "apple", "papaya")  
    
      
    
    # printing the given tuple for reference  
    
    print("Given Tuple :", fruits_tuple)  
    
      
    
    print("Looping with 'for' Loop:")  
    
    i = 1  
    
    # iterating through the tuple  
    
    for fruit in fruits_tuple:  
    
        # printing the element  
    
        print(i, "-", fruit)  
    
        i += 1  
    
      
    
    print("\nLooping with 'while' Loop:")  
    
    # initializing an iterable with 0  
    
    j = 0  
    
    # using the while loop to iterate through the tuple  
    
    while j < len(fruits_tuple):  
    
        # printing the element of the tuple  
    
        print(j + 1, "-", fruits_tuple[j])  
    
        # incrementing the index value by 1  
    
        j += 1

    Output:

    Given Tuple : ('mango', 'orange', 'banana', 'apple', 'papaya')
    Looping with 'for' Loop:
    1 - mango
    2 - orange
    3 - banana
    4 - apple
    5 - papaya
    
    Looping with 'while' Loop:
    1 - mango
    2 - orange
    3 - banana
    4 - apple
    5 - papaya
    

    Explanation:

    In this example, we have created a tuple containing some elements and printed it for reference. We have then used the ‘for’ and ‘while’ loop to iterate through each element of tuple and printed them. As a result, the elements of the tuple are printed successfully.

    Tuple Operators in Python

    The following table displays the list of different operators to work with Python tuples.

    S. No.Python OperatorPython ExpressionResultDescription
    1+(2, 4, 6) + (3, 5, 7)(2, 4, 6, 3, 5, 7)Concatenation
    2*(‘Apple’, ) * 3(‘Apple’,
    ‘Apple’,
    ‘Apple’)
    Repetition
    3in, not in4 in (2, 4, 6, 8, 10)TrueMembership

    Python Example for Tuple Operators

    Let us now consider the following example illustrating the use of different operators on Tuples in Python.

    Example

    # Python program to illustrate the use of operators in the case of tuples  
    
      
    
    # creating a tuple for concatenation  
    
    vegetables_tuple = ('Potato', 'Tomato', 'Onion')  
    
    # printing the tuple  
    
    print("Vegetables Tuple =>", vegetables_tuple)  
    
      
    
    # creating another tuple for concatenation  
    
    fruits_tuple = ('Mango', 'Apple', 'Orange')  
    
    # printing the tuple  
    
    print("Fruits Tuple =>", fruits_tuple)  
    
      
    
    # concatenating the tuples using the + operator  
    
    tuple_of_food_items = vegetables_tuple + fruits_tuple  
    
    # printing the resultant tuple  
    
    print("Concatenated Tuple: Tuple of Food Items =>", tuple_of_food_items)  
    
      
    
    # creating a tuple for repetition  
    
    sampleTuple = ('Mango', 'Grapes', 'Banana')  
    
      
    
    # printing the original tuple  
    
    print("Original tuple =>", sampleTuple)  
    
      
    
    # Repeating the tuple elements for 4 times using the * operator  
    
    sampleTuple = sampleTuple * 4  
    
      
    
    # printing the new tuple  
    
    print("New tuple =>", sampleTuple)  
    
      
    
    # creating a tuple for membership  
    
    test_tuple = (12, 23, 35, 76, 84)  
    
    # printing the tuple  
    
    print("Given tuple =>", test_tuple)  
    
      
    
    # test cases  
    
    n = 35  
    
    m = 47  
    
      
    
    # checking whether variable n and m belongs to the given tuple or not using the membership operator  
    
    if n in test_tuple:  
    
        print("Yes.", n, "is present in the tuple", test_tuple)  
    
    else:  
    
        print("No.", n, "is NOT present in the given tuple.")  
    
      
    
    if m in test_tuple:  
    
        print("Yes.", m, "is present in the tuple", test_tuple)  
    
    else:  
    
        print("No.", m, "is NOT present in the given tuple.")

    Output:

    Vegetables Tuple => ('Potato', 'Tomato', 'Onion')
    Fruits Tuple => ('Mango', 'Apple', 'Orange')
    Concatenated Tuple: Tuple of Food Items => ('Potato', 'Tomato', 'Onion', 'Mango', 'Apple', 'Orange')
    Original tuple => ('Mango', 'Grapes', 'Banana')
    New tuple => ('Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana', 'Mango', 'Grapes', 'Banana')
    Given tuple => (12, 23, 35, 76, 84)
    Yes. 35 is present in the tuple (12, 23, 35, 76, 84)
    No. 47 is NOT present in the given tuple.
    

    Explanation:

    In this example, we have used the concatenation operator ‘+’, to add the elements of two different tuples in a new tuple. We have used the repetition operator ‘*’ to repeat the elements of the tuple for given number of times. We have also used the membership operator ‘in’ to check if the passed item is a member of the tuple.

    Tuple Methods in Python

    Python tuple, being a collection of immutable items, makes it difficult to alter or modify the initialized objects of the tuple. However, Python offers two built-in methods to work with tuples. These methods are as listed below:

    1. count()
    2. index()

    Let us now discuss these methods in detail with the help of some examples.

    The count() Method

    The count() method is a built-in Python method to count the occurrence of the specified element in a tuple.

    Syntax:

    It has the following syntax:

    tuple_name.count(item)  

    Parameter:

    • item (required): The item parameter is the item to be searched in the tuple.

    Return:

    • The number of times the specified item appeared in the tuple.

    Let us now look at the following example illustrating the use of the count() method in the case of Python tuples.

    Example

    # Python program to demonstrate the use of count() method in the case of tuples  
    
      
    
    # creating tuples  
    
    T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)  
    
    T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')  
    
      
    
    # counting the occurrence of 2 in the tuple T1  
    
    resultOne = T1.count(2)  
    
      
    
    # counting the occurence of 'Mango' in the tuple T2  
    
    resultTwo = T2.count('Mango')  
    
      
    
    # printing the results  
    
    print("Tuple T1 =>", T1)  
    
    print("Total Occurrence of 2 in T1 =>", resultOne)  
    
      
    
    # printing the results  
    
    print("\nTuple T2 =>", T2)  
    
    print("Total Occurrence of 'Mango' in T2 =>", resultTwo)

    Output:

    Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
    Total Occurrence of 2 in T1 => 5
    
    Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
    Total Occurrence of 'Mango' in T2 => 4
    

    Explanation:

    In this example, we have used the count() method to count the occurrence of passed variables in the given tuple.

    The index() Method

    The index() method is a built-in Python method to search for a specified element in the tuple and return its position.

    Syntax:

    It has the following syntax:

    tuple_name.index(item)  

    Parameter:

    • item (required): The item parameter is the item to be searched in the tuple.
    • start (optional): The start parameter indicates the starting index from where the searching is begun.
    • end (optional): The end parameter indicates the ending index till where the searching is done.

    Return:

    • An Integer Value indicating the index of the first occurrence of the specified value.

    Let us now look at the following example illustrating the use of the index() method in the case of Python tuples.

    Example

    # Python program to demonstrate the use of index() method in the case of tuples  
    
      
    
    # creating tuples  
    
    T1 = (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)  
    
    T2 = ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')  
    
      
    
    # searching for the occurrence of 2 in the tuple T1  
    
    resultOne = T1.index(2)  
    
    resultTwo = T1.index(2, 5)  
    
      
    
    # searching for the occurence of 'Mango' in the tuple T2  
    
    resultThree = T2.index('Mango')  
    
    resultFour = T2.index('Mango', 3)  
    
      
    
    # printing the results  
    
    print("Tuple T1 =>", T1)  
    
    print("First Occurrence of 2 in T1 =>", resultOne)  
    
    print("First Occurrence of 2 after 5th index in T1 =>", resultTwo)  
    
      
    
    # printing the results  
    
    print("\nTuple T2 =>", T2)  
    
    print("First Occurrence of 'Mango' in T2 =>", resultThree)  
    
    print("First Occurrence of 'Mango' after 3rd index in T2 =>", resultFour)

      Output:

      Tuple T1 => (0, 2, 3, 6, 4, 2, 5, 6, 3, 2, 2, 6, 7, 2, 7, 8, 0, 1, 9, 1)
      First Occurrence of 2 in T1 => 1
      First Occurrence of 2 after 5th index in T1 => 5
      
      Tuple T2 => ('Apple', 'Orange', 'Mango', 'Apple', 'Banana', 'Mango', 'Mango', 'Orange', 'Mango', 'Apple')
      First Occurrence of 'Mango' in T2 => 2
      First Occurrence of 'Mango' after 3rd index in T2 => 5
      

      Explanation:

      In this example, we have used the index() method to return the index value of the first occurrence of the passed elements in the given tuple.

      Some Other Methods for Python Tuples

      Apart from the count() and index() methods, we have some other methods to work with tuples in Python. These methods as follows:

      • max()
      • min()
      • len()

      Let us now discuss these methods in detail.

      The max() Method:

      Python’s max() method is used to return the maximum value in the tuple.

      Syntax:

      It has the following syntax:

      max(object)  

      Parameter:

      • object (required): The object parameter can be any iterable such as Tuple, List, etc.

      Return:

      • The largest element from that iterable (Tuple, List, etc.)

      Let us now consider the following example illustrating the use of the max() method to find the largest integer in the given tuple.

      Example

      # Python program to demonstrate the use of max() method in the case of tuples  
      
        
      
      # creating a tuple  
      
      sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
      
        
      
      # printing the tuple for reference  
      
      print("Given Tuple =>", sampleTuple)  
      
        
      
      # using the max() method to find the largest element in the tuple  
      
      largest_element = max(sampleTuple)  
      
        
      
      # printing the result for the users  
      
      print("The Largest Element in the Given Tuple =>", largest_element)

        Output:

        Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
        The Largest Element in the Given Tuple => 9
        

        Explanation:

        In the example, we have used the max() method on the given tuple to find the largest element in it.

        The min() Method

        Python provides a method called min() to find the minimum value in the tuple.

        Syntax:

        It has the following syntax:

        min(object)  

        Parameter:

        • object (required): The object parameter can be any iterable such as Tuple, List, etc.

        Return:

        • The smallest element from that iterable (Tuple, List, etc.)

        Let us now consider the following example illustrating the use of the min() method to find the smallest integer in the given tuple.

        Example

        # Python program to demonstrate the use of min() method in the case of tuples  
        
          
        
        # creating a tuple  
        
        sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
        
          
        
        # printing the tuple for reference  
        
        print("Given Tuple =>", sampleTuple)  
        
          
        
        # using the min() method to find the smallest element in the tuple  
        
        smallest_element = min(sampleTuple)  
        
          
        
        # printing the result for the users  
        
        print("The Smallest Element in the Given Tuple =>", smallest_element)

          Output:

          Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
          The Smallest Element in the Given Tuple => 0
          

          Explanation:

          In the example, we have used the min() method on the given tuple to find the smallest element in it.

          The len() Method

          Python’s len() method is used to find the length of the given sequence such as Tuple, List, String, etc.

          Syntax:

          It has the following syntax:

          len(object)  

          Parameter:

          • object (required): The object parameter can be any iterable such as Tuple, List, etc.

          Return:

          • The number of elements in that iterable (Tuple, List, etc.)

          Let us now consider the following example illustrating the use of the len() method to find the length of the given tuple.

          Example

          # Python program to demonstrate the use of len() method in the case of tuples  
          
            
          
          # creating a tuple  
          
          sampleTuple = (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)  
          
            
          
          # printing the tuple for reference  
          
          print("Given Tuple =>", sampleTuple)  
          
            
          
          # using the len() method to find the length of the tuple  
          
          length_of_tuple = len(sampleTuple)  
          
            
          
          # printing the result for the users  
          
          print("Number of Elements in the Given Tuple =>", length_of_tuple)

            Output:

            Given Tuple => (5, 3, 6, 1, 2, 8, 7, 9, 0, 4)
            Number of Elements in the Given Tuple => 10
            

            Explanation:

            In the example, we have used the len() method on the given tuple to find the total number of elements present in it.

            Conclusion

            In conclusion, Python tuple is an essential data structure that allows us to store a collection of items in a single variable. Unlike lists, tuples are immutable, meaning their values cannot be changed after creation. They are useful when we want to ensure data remains constant throughout the program. Tuples can store multiple data types, support indexing and slicing, and are more memory-efficient than lists. Understanding how to use tuples helps improve the reliability and performance of our Python code.

          • Python List Methods

            Python Lists offers a wide range of built-in methods to manipulate data efficiently. List in Python, is an ordered and mutable data type allowing us to store multiple values in a single variable.

            Let us take a look at various List methods available in Python.

            MethodDescription
            append()This method is utilized to add an element x to the end of the list.
            extend()This method is utilized to add all elements of an iterable (list, tuple, etc.) to the list.
            insert()This method is utilized to insert an element x at index i.
            remove()This method is utilized to remove the first occurrence of x. It raises ValueError if x is not found.
            pop()This method is utilized to remove and returns the element at index i (default is the last element).
            clear()This method is utilized to remove all elements, making the list empty.
            index()This method is utilized to return the first index of x between start and end. It raises ValueError if not found.
            count()This method is utilized to return the number of occurrences of x in the list.
            sort()This method is utilized to sort the list in place (default is ascending).
            reverse()This method is utilized to reverse the order of the list in place.
            copy()This method is utilized to return a shallow copy of the list.

            1) append()

            The append() method in Python allows us to add an element at the end of the list.

            Syntax:

            It has the following syntax:

            list_name.append(item)   

            Python append() Method Example

            Let us take an example to demonstrate the append() method in Python.

            Example

            # python program to show the use of list append() method  
            
              
            
            # creating a list  
            
            list_of_fruits = ['apple', 'mango', 'banana', 'orange', 'guava']  
            
              
            
            # printing the list  
            
            print("List of Fruits:", list_of_fruits)  
            
              
            
            # using the append() method  
            
            list_of_fruits.append('grapes')  
            
              
            
            # printing the updated list  
            
            print("Updated List of Fruits:", list_of_fruits)

              Output:

              List of Fruits: ['apple', 'mango', 'banana', 'orange', 'guava']
              Updated List of Fruits: ['apple', 'mango', 'banana', 'orange', 'guava', 'grapes']
              

              Explanation:

              In the above example, we have used the append() method to add a new element ‘grapes’ at the end of the given list.

              2) extend()

              The extend() method in Python allows us to append all the elements from an iterable (list, tuple, set, etc.) at the end of the list.

              Syntax:

              It has the following syntax:

              list_name.extend(iterable)  

              Python extend() Method Example

              Let us take an example to demonstrate the extend() method in Python.

              Example

              # python program to show the use of list extend() method  
              
                
              
              # initializing the lists  
              
              shopping_list = ['milk', 'bread', 'butter']  
              
              new_items = ['eggs', 'apples', 'coffee']  
              
                
              
              # printing the lists  
              
              print("Old Shopping List:", shopping_list)  
              
              print("New Items:", new_items)  
              
                
              
              # using the extend() method  
              
              shopping_list.extend(new_items)  
              
                
              
              # printing the updated list  
              
              print("Updated Shopping List:", shopping_list)

                Output:

                Old Shopping List: ['milk', 'bread', 'butter']
                New Items: ['eggs', 'apples', 'coffee']
                Updated Shopping List: ['milk', 'bread', 'butter', 'eggs', 'apples', 'coffee']
                

                Explanation:

                In the above example, we have used the extend() method to add an iterable at the end of the given list.

                3) insert()

                The insert() method in Python allows us to insert an the elements at a specified position in the list.

                Syntax:

                It has the following syntax:

                list_name.insert(index, item)  

                Python insert() Method Example

                Let us take an example to illustrate how the insert() method works in Python.

                Example

                # python program to show the use of list insert() method  
                
                  
                
                # initializing the list  
                
                shopping_list = ['milk', 'bread', 'butter', 'coffee']  
                
                  
                
                # printing the list  
                
                print("Old Shopping List:", shopping_list)  
                
                  
                
                # using the insert() method  
                
                shopping_list.insert(2, 'eggs')  
                
                  
                
                # printing the updated list  
                
                print("New Shopping List:", shopping_list)

                  Output:

                  Old Shopping List: ['milk', 'bread', 'butter', 'coffee']
                  New Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
                  

                  Explanation:

                  In the above example, we have used the insert() method to insert item ‘eggs’ at the second index of the given list.

                  4) remove()

                  The remove() method in Python allows us to remove the first occurrence of the specified element from the list.

                  Syntax:

                  It has the following syntax:

                  list_name.remove(item)  

                  Python remove() Method Example

                  Let us take an example to demonstrate the remove() method in Python.

                  Example

                  # python program to show the use of list remove() method  
                  
                    
                  
                  # initializing the list  
                  
                  shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']  
                  
                    
                  
                  # printing the list  
                  
                  print("Old Shopping List:", shopping_list)  
                  
                    
                  
                  # using the remove() method  
                  
                  shopping_list.remove('butter')  
                  
                    
                  
                  # printing the updated list  
                  
                  print("New Shopping List:", shopping_list)

                    Output:

                    Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
                    New Shopping List: ['milk', 'bread', 'eggs', 'coffee']
                    

                    Explanation:

                    In the above example, we have used the remove() method to remove item ‘butter’ from the given list.

                    5) pop()

                    The pop() method in Python allows us to remove and return the element from the specified index of the given list.

                    Syntax:

                    It has the following syntax:

                    list_name.pop(index)  

                    Python pop() Method Example

                    Let us take an example to demonstrate the pop() method in Python.

                    Example

                    # python program to show the use of list pop() method  
                    
                      
                    
                    # initializing the list  
                    
                    shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']  
                    
                      
                    
                    # printing the list  
                    
                    print("Old Shopping List:", shopping_list)  
                    
                      
                    
                    # using the pop() method  
                    
                    popped_item = shopping_list.pop(1)  
                    
                      
                    
                    # printing the updated list  
                    
                    print("New Shopping List:", shopping_list)  
                    
                    print("Popped Item:", popped_item) # popped element

                      Output:

                      Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
                      New Shopping List: ['milk', 'eggs', 'butter', 'coffee']
                      Popped Item: bread
                      

                      Explanation:

                      In the above example, we have used the pop() method to remove and return the item at index ‘2’ from the given list.

                      6) clear()

                      The clear() method in Python allows us to remove all the elements from the list making it empty.

                      Syntax:

                      It has the following syntax:

                      list_name.clear()  

                      Python clear() Method Example

                      Let us take an example to demonstrate the clear() method in Python.

                      Example

                      # python program to show the use of list clear() method  
                      
                        
                      
                      # initializing the list  
                      
                      shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']  
                      
                        
                      
                      # printing the list  
                      
                      print("Old Shopping List:", shopping_list)  
                      
                        
                      
                      # using the clear() method  
                      
                      shopping_list.clear()  
                      
                        
                      
                      # printing the updated list  
                      
                      print("New Shopping List:", shopping_list)

                        Output:

                        Old Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
                        New Shopping List: []
                        

                        Explanation:

                        In the above example, we have used the clear() method to remove all the elements from the given list.

                        7) index()

                        The index() method in Python returns the first index of the element within start and end.

                        Syntax:

                        It has the following syntax:

                        list_name.index(item, start, end)  

                        Python index() Method Example

                        Let us take an example to demonstrate the index() method in Python.

                        Example

                        # python program to show the use of list index() method  
                        
                          
                        
                        # initializing the list  
                        
                        shopping_list = ['milk', 'bread', 'eggs', 'butter', 'coffee']  
                        
                          
                        
                        # printing the lists  
                        
                        print("Shopping List:", shopping_list)  
                        
                          
                        
                        # using the index() method  
                        
                        item_index = shopping_list.index('butter')  
                        
                          
                        
                        # printing the index of the item  
                        
                        print("Index of butter:", item_index)

                          Output:

                          Shopping List: ['milk', 'bread', 'eggs', 'butter', 'coffee']
                          Index of butter: 3
                          

                          Explanation:

                          In the above example, we have used the index() method to find the first occurrence of the element from the given list.

                          8) count()

                          The count() method in Python allows us to all the occurrence of the element in the list.

                          Syntax:

                          It has the following syntax:

                          list_name.count(item)  

                          Python count() Method Example

                          Let us take an example to demonstrate the count() method in Python.

                          Example

                          # python program to show the use of list count() method  
                          
                            
                          
                          # initializing the list  
                          
                          shopping_list = ['milk', 'bread', 'egg', 'milk', 'butter', 'coffee', 'egg', 'flour', 'egg']  
                          
                            
                          
                          # printing the lists  
                          
                          print("Shopping List:", shopping_list)  
                          
                            
                          
                          # using the count() method  
                          
                          item_count = shopping_list.count('egg')  
                          
                            
                          
                          # printing the count of the item  
                          
                          print("No. of Eggs:", item_count)

                            Output:

                            Shopping List: ['milk', 'bread', 'egg', 'milk', 'butter', 'coffee', 'egg', 'flour', 'egg']
                            No. of Eggs: 3
                            

                            Explanation:

                            In the above example, we have used the count() method to find all the occurrences of ‘egg’ in the given list.

                            9) sort()

                            The sort() method in Python allows us to sort the list in place.

                            Syntax:

                            It has the following syntax:

                            list_name.sort(reverse = False, key = None)  

                            Python sort() Method Example

                            Let us take an example to illustrate how the sort() method works in Python.

                            Example

                            # python program to show the use of list sort() method  
                            
                              
                            
                            # initializing the list  
                            
                            fruit_basket = ['mango', 'apple', 'orange', 'banana', 'grapes']  
                            
                              
                            
                            # printing the list  
                            
                            print("Unsorted Fruit Basket:", fruit_basket)  
                            
                              
                            
                            # using the sort() method  
                            
                            fruit_basket.sort()  
                            
                              
                            
                            # printing the updated list  
                            
                            print("Sorted Fruit Basket:", fruit_basket)

                              Output:

                              Unsorted Fruit Basket: ['mango', 'apple', 'orange', 'banana', 'grapes']
                              Sorted Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
                              

                              Explanation:

                              In the above example, we have used the sort() method to sort the elements of the given list in ascending order.

                              10) reverse()

                              The reverse() method in Python allows us to reverse the list in place.

                              Syntax:

                              It has the following syntax:

                              list_name.reverse()  

                              Python reverse() Method Example

                              Let us take an example to illustrate how the reverse() method works in Python.

                              Example

                              # python program to show the use of list reverse() method  
                              
                                
                              
                              # initializing the list  
                              
                              fruit_basket = ['apple', 'banana', 'grapes', 'mango', 'orange']  
                              
                                
                              
                              # printing the list  
                              
                              print("Fruit Basket:", fruit_basket)  
                              
                                
                              
                              # using the reverse() method  
                              
                              fruit_basket.reverse()  
                              
                                
                              
                              # printing the updated list  
                              
                              print("Reversed Fruit Basket:", fruit_basket)

                                Output:

                                Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
                                Reversed Fruit Basket: ['orange', 'mango', 'grapes', 'banana', 'apple']
                                

                                Explanation:

                                In the above example, we have used the reverse() method to reverse the given list.

                                11) copy()

                                The copy() method in Python allows us to create a shallow copy of the list.

                                Syntax:

                                It has the following syntax:

                                list_name.copy()  

                                Python copy() Method Example

                                Let us take an example to illustrate how the copy() method works in Python.

                                Example

                                # python program to show the use of list copy() method  
                                
                                  
                                
                                # initializing the list  
                                
                                fruit_basket = ['apple', 'banana', 'grapes', 'mango', 'orange']  
                                
                                  
                                
                                # printing the list  
                                
                                print("Fruit Basket:", fruit_basket)  
                                
                                  
                                
                                # using the copy() method  
                                
                                new_fruit_basket = fruit_basket.copy()  
                                
                                  
                                
                                # printing the copied list  
                                
                                print("Copied Fruit Basket:", new_fruit_basket)

                                  Output:

                                  Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
                                  Copied Fruit Basket: ['apple', 'banana', 'grapes', 'mango', 'orange']
                                  

                                  Explanation:

                                  In the above example, we have used the copy() method to create a shallow copy of the given list.

                                • Python Lists

                                  In Python, a list is a built-in data structure that allows us to store multiple items in a single variable. Lists are one of the most used data structures in Python because they are mutable, ordered, and can hold different types of elements. Lists provide a flexible way to handle collections of data and come with many useful built-in methods.

                                  Let us take a look at a simple example of a list.

                                  Example

                                  # creating a list  
                                  
                                  L = [20, 'Python App', 35.75, [20, 40, 60]]  
                                  
                                    
                                  
                                  print(L)

                                    Output:

                                    [20, 'Python App', 35.75, [20, 40, 60]]

                                    Explanation:

                                    In the above example, we have created a simple list consisting of four elements of different data types. Each element in this list is indexed, meaning it can be accessed using its position in the list, as shown below:

                                    • L[0] = 20 (Integer)
                                    • L[1] = ‘Python App’ (String)
                                    • L[2] = 35.75 (Float)
                                    • L[3] = [20, 40, 60] (Nested List)

                                    Characteristics of Python Lists

                                    List in Python is a data structure, which is:

                                    • Ordered: The data elements of list maintain their order of insertion. If an element is inserted at a specific index, it remains there unless it is explicitly changed.
                                    • Changeable (Mutable): Lists in Python allow modification of their elements after creation.

                                    Let us look at the following example showing that Lists are changeable.

                                    Example

                                    # creating a list  
                                    
                                    my_lst = [25, 16.25, 'Python App', [20, 40, 60], 3e8]  
                                    
                                      
                                    
                                    # changing the element of the list  
                                    
                                    my_lst[1] = 'welcome'  
                                    
                                    print(my_lst)

                                      Output:

                                      [25, 'welcome', 'Python App', [20, 40, 60], 300000000.0]
                                      

                                      In this example, we have initialized a list and used the indexing to change its element.

                                      • Heterogeneous (Different Data Types): A single list can store multiple data types like integers, strings, floats, and even another list.

                                      Let us take a look at the following example showing that List is a heterogeneous data structure.

                                      Example

                                      # creating a list  
                                      
                                      mixed_lst = [10, 'Hello', 5.23, [7, 12]]  
                                      
                                        
                                      
                                      print(mixed_lst)

                                      Output:

                                      [10, 'Hello', 5.23, [7, 12]]
                                      

                                      In this example, we have initialized a list consisting of multiple data types, such as integer, string, float, and a list.

                                      • Contains Duplicates: List is a data structure that can store duplicate values.

                                      Let us take an example showing that List allows duplicates.

                                      Example

                                      # creating a list  
                                      
                                      dup_lst = [12, 51, 12, 5, 3, 5, 77, 42, 2, 12, 12, 6, 6]  
                                      
                                        
                                      
                                      print(dup_lst)

                                        Output:

                                        [12, 51, 12, 5, 3, 5, 77, 42, 2, 12, 12, 6, 6]
                                        

                                        In this example, we have initialized a list consisting of duplicate values.

                                        Operations on List in Python

                                        There are many operations that we can perform on Python list. Some of them are listed below:

                                        1. Creating a List
                                        2. Accessing List Elements
                                        3. Adding Elements to List
                                        4. Updating Elements into List
                                        5. Removing Elements from the List
                                        6. Iterating Over Lists

                                        Let us now see the implementation of these list operations with examples.

                                        Creating a List

                                        Lists in Python can be created by enclosing elements within square brackets [], separated by commas.

                                        Let us see an example showing the way of creating a list.

                                        Example

                                        # Creating lists  
                                        
                                        empty_list = []  
                                        
                                        numbers = [11, 4, 23, 71, 58]  
                                        
                                        mixed_list = [1, "Hello", 6.74, True]  
                                        
                                          
                                        
                                        print(empty_list)  
                                        
                                        print(numbers)  
                                        
                                        print(mixed_list)

                                          Output:

                                          []
                                          [11, 4, 23, 71, 58]
                                          [1, 'Hello', 6.74, True]
                                          

                                          Explanation:

                                          In the above example, we have created three types of lists – empty list, list consisting of only integer values, and list consisting of elements of different data types. We have then printed them for reference.

                                          Accessing List Elements

                                          Elements in a list can be accessed using indexing. Python uses zero-based indexing, meaning the first element has an index of 0. We can use the index number enclosed with the square brackets ‘[]’ to access the element present at the given position.

                                          Here is an example showing the method of accessing the element in a given list.

                                          Example

                                          # Creating lists  
                                          
                                          my_list = [15, 23, 47, 32, 94]  
                                          
                                            
                                          
                                          print(my_list[0])    
                                          
                                          print(my_list[-1])

                                            Output:

                                            15
                                            94
                                            

                                            Explanation:

                                            In the above example, we have created three types of lists – empty list, list consisting of only integer values, and list consisting of elements of different data types. We have then printed them for reference.

                                            Adding Elements to the List

                                            Python offers accessibility to add elements to a list. This can be achieved using the various options available for us:

                                            • append(): Adds a single element to the end of the list.
                                            • insert(): Inserts an element at a specific index.
                                            • extend(): Adds multiple elements to the end of the list.

                                            Here is an example showing different methods to add elements to a list.

                                            Example

                                            # creating a list  
                                            
                                            my_lst = [7, 3, 4]  
                                            
                                              
                                            
                                            # Method 1: using append()  
                                            
                                            my_lst.append(6)  
                                            
                                            print(my_lst)  
                                            
                                              
                                            
                                            # Method 2: using insert()  
                                            
                                            my_lst.insert(1, 13)  
                                            
                                            print(my_lst)  
                                            
                                              
                                            
                                            # Method 3: using extend()  
                                            
                                            my_lst.extend([14, 43, 37])  
                                            
                                            print(my_lst)

                                              Output:

                                              [7, 3, 4, 6]
                                              [7, 13, 3, 4, 6]
                                              [7, 13, 3, 4, 6, 14, 43, 37]
                                              

                                              Explanation:

                                              In the above example, we have created a list and used three different methods – append(), insert() and extend(), in order to insert items in the list. As a result, the append() method has added an item at the end of the list. The insert() method has added an item at the second place in the list. The extend() method has added multiple elements altogether at the end of the list.

                                              Updating Elements into a List

                                              Elements in a list can be updated using indexing. The following is an example showing the way of updating items in a list.

                                              Example

                                              # creating a list  
                                              
                                              my_lst = [17, 23, 35]  
                                              
                                                
                                              
                                              # Updating the second element  
                                              
                                              my_lst[1] = 52  
                                              
                                                
                                              
                                              print(my_lst)

                                                Output:

                                                [17, 52, 35]
                                                

                                                Explanation:

                                                In the above example, we have created a list. We then used the indexing to update the second element of the list.

                                                Removing Elements from the List

                                                Python provides several methods to remove elements from a list:

                                                • remove(value): Removes the first occurrence of the value.
                                                • pop(index): Removes the element at a specific index (or the last element by default).
                                                • del statement: Deletes an element or the entire list.

                                                Let us take a look at the following example showing several ways to remove an item from the list.

                                                Example

                                                # creating a list  
                                                
                                                my_lst = [14, 25, 43, 2, 33]  
                                                
                                                  
                                                
                                                # Method 1: using remove()  
                                                
                                                my_lst.remove(43)  
                                                
                                                print(my_lst)  
                                                
                                                  
                                                
                                                # Method 2: using pop()  
                                                
                                                my_lst.pop(-1)  
                                                
                                                print(my_lst)  
                                                
                                                  
                                                
                                                # Method 3: using del keyword  
                                                
                                                del my_lst[0]  
                                                
                                                print(my_lst)

                                                  Output:

                                                  [14, 25, 2, 33]
                                                  [14, 25, 2]
                                                  [25, 2]
                                                  

                                                  Explanation:

                                                  In the above example, we have created a list and used three different approaches – remove(), pop() and del keyword, in order to remove items from the list. As a result, remove() method has removed the specified item from the list. The pop() method has removed the element at the specified index from the list. The del keyword has deleted the element from the list at the specified index.

                                                  Iterating Over Lists

                                                  In Python, we can iterate over lists using the loops. Let us take an example showing the use of ‘for’ loop and ‘while’ loop to iterate over the elements of a given list.

                                                  Example

                                                  # creating a list  
                                                  
                                                  my_lst = [12, 23, 9, 17, 41]  
                                                  
                                                    
                                                  
                                                  print("Iterating List using 'for' loop:")  
                                                  
                                                  # Using for loop  
                                                  
                                                  for ele in my_lst:  
                                                  
                                                      print(ele)  
                                                  
                                                    
                                                  
                                                  print("\nIterating List using 'while' loop:")  
                                                  
                                                  # Using while loop  
                                                  
                                                  i = 0  
                                                  
                                                  while i < len(my_lst):  
                                                  
                                                      print(my_lst[i])  
                                                  
                                                      i += 1

                                                    Output:

                                                    Iterating List using 'for' loop:
                                                    12
                                                    23
                                                    9
                                                    17
                                                    41
                                                    
                                                    Iterating List using 'while' loop:
                                                    12
                                                    23
                                                    9
                                                    17
                                                    41
                                                    

                                                    Explanation:

                                                    In this example, we have created a list. We have then used the for loop to iterate over the list. We then used the while loop where we set the initial index value, i as 0; and incremented it while printing the element of the current index from the list.

                                                    Nested Lists in Python

                                                    Nested List is a list in Python that consists of multiple sub-lists separated by commas. The elements in each sub-list can be of different data types. The inner lists (or sub-list) can again consist of other lists, giving rise to the multiple levels of nesting.

                                                    In Python, we can use nested lists to create hierarchical data structures, matrices or simply, a list of lists. Python provides various tools to handle nested lists efficiently and effectively, allowing users to perform standard functions on them.

                                                    Let us see an example showing the different operations on nested list in Python.

                                                    Example

                                                    # creating a nested list  
                                                    
                                                    nested_lst = [[14, 6, 8], [13, 18, 25], [72, 48, 69]]  
                                                    
                                                      
                                                    
                                                    print("Nested List:", nested_lst)  
                                                    
                                                      
                                                    
                                                    print("\nAccessing Elements of Nested List:")  
                                                    
                                                    # Accessing elements  
                                                    
                                                    print("nested_lst[0]:", nested_lst[0])  
                                                    
                                                    print("nested_lst[0][1]:", nested_lst[0][1])  
                                                    
                                                      
                                                    
                                                    print("\nIterating through Nested list using 'for' loop:")  
                                                    
                                                    # Iterating through a nested list  
                                                    
                                                    for sublist in nested_lst:  
                                                    
                                                      for item in sublist:  
                                                    
                                                        print(item)  
                                                    
                                                      
                                                    
                                                    print("\nAdding element to Nested list:")  
                                                    
                                                    # Adding elements  
                                                    
                                                    nested_lst[0].append(10)  
                                                    
                                                    print("New Nested List:", nested_lst)

                                                      Output:

                                                      Nested List: [[14, 6, 8], [13, 18, 25], [72, 48, 69]]
                                                      
                                                      Accessing Elements of Nested List:
                                                      nested_lst[0]: [14, 6, 8]
                                                      nested_lst[0][1]: 6
                                                      
                                                      Iterating through Nested list using 'for' loop:
                                                      14
                                                      6
                                                      8
                                                      13
                                                      18
                                                      25
                                                      72
                                                      48
                                                      69
                                                      
                                                      Adding element to Nested list:
                                                      New Nested List: [[14, 6, 8, 10], [13, 18, 25], [72, 48, 69]]
                                                      

                                                      Explanation:

                                                      In the above example, we have created a nested list. We then used the indexing to access the elements of the list. In first case, we have accessed the element of the outer list using nested_lst[0], which returns the inner list as an output, i.e., [14, 6, 8]. In second case, we have accessed the element of the inner list using nested_lst[0][1], which returns the element of the inner list, i.e., 6. We then perform iteration on the nested list using the nested for loop. At last, we have added an element to the nested list using the append() method.

                                                      Finding the Length of a List

                                                      Python provides a built-in function called len() in order to determine the number of elements in a list.

                                                      Syntax:

                                                      len(list_name)  

                                                      Let us take an example showing the use of the len() function on lists.

                                                      Example

                                                      # creating a list  
                                                      
                                                      lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                      
                                                        
                                                      
                                                      # using the len() function to find the size of the list  
                                                      
                                                      no_of_ele = len(lst_one)  
                                                      
                                                        
                                                      
                                                      print("Given List:", lst_one)  
                                                      
                                                      print("Number of Elements in the given list:", no_of_ele) 

                                                        Output:

                                                        Given List: [15, 61, 23, 6, 87, 5, 93]
                                                        Number of Elements in the given list: 7
                                                        

                                                        Explanation:

                                                        In the above example, we have created a list of some integers. We have then used the len() function to find the size of the list and store it in a variable. We then printed the list and the variable value as a result.

                                                        Sorting a List

                                                        Python provides a method called sort() that allows users to sort the elements of a list in place. Let us look at an example showing the working of sort() method.

                                                        Example

                                                        # creating a list  
                                                        
                                                        lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                        
                                                        print("Given List:", lst_one)  
                                                        
                                                          
                                                        
                                                        # sorting the list in ascending order (by default)  
                                                        
                                                        lst_one.sort()  
                                                        
                                                        print("Sorted List:", lst_one)

                                                        Output:

                                                        Given List: [15, 61, 23, 6, 87, 5, 93]
                                                        Sorted List: [5, 6, 15, 23, 61, 87, 93]
                                                        

                                                        Explanation:

                                                        In the above example, we have created a list and used the sort() method to sort it into ascending order.

                                                        Python Sorted List Example

                                                        Python also offers a function called sorted() which works similar to the sort() method; however, it returns a new list.

                                                        Let us take a look at the following example showing the use of sorted() function.

                                                        Example

                                                        # creating a list  
                                                        
                                                        lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                        
                                                          
                                                        
                                                        # sorting the list  
                                                        
                                                        new_lst = sorted(lst_one)  
                                                        
                                                          
                                                        
                                                        print("Given List:", lst_one)  
                                                        
                                                        print("Sorted List:", new_lst)

                                                        Output:

                                                        Given List: [15, 61, 23, 6, 87, 5, 93]
                                                        Sorted List: [5, 6, 15, 23, 61, 87, 93]
                                                        

                                                        Explanation:

                                                        In the example, we have created a list and used the sorted() function to sort the list.

                                                        Reversing a List

                                                        Python List provides a method called reverse() that allows users to reverse the order of the elements in the list.

                                                        Let us see the following example showing the use of reverse() method.

                                                        Example

                                                        # creating a list  
                                                        
                                                        lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                        
                                                        print("Given List:", lst_one)  
                                                        
                                                          
                                                        
                                                        # reversing the list  
                                                        
                                                        lst_one.reverse()  
                                                        
                                                        print("Reversed List:", lst_one)

                                                          Output:

                                                          Given List: [15, 61, 23, 6, 87, 5, 93]
                                                          Reversed List: [93, 5, 87, 6, 23, 61, 15]
                                                          

                                                          Explanation:

                                                          In the above example, we have created a list and used the reverse() method to reverse the order of the elements in the given list.

                                                          Finding the Largest and Smallest Number in a List

                                                          To find the largest and smallest number in a list, we can make use of max() and min() functions as shown in the following example:

                                                          Example

                                                          # creating a list  
                                                          
                                                          lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                          
                                                          print("Given List:", lst_one)  
                                                          
                                                            
                                                          
                                                          # finding largest and smallest number  
                                                          
                                                          print("Largest Number:", max(lst_one))  
                                                          
                                                          print("Smallest Number:", min(lst_one))

                                                          Output:

                                                          Given List: [15, 61, 23, 6, 87, 5, 93]
                                                          Largest Number: 93
                                                          Smallest Number: 5
                                                          

                                                          Explanation:

                                                          In the above example, we have created a list. We then used the max() function to determine the largest number in the given list. We also used the min() function to find the smallest number.

                                                          Calculating Sum of Elements in a List

                                                          In order to calculate the sum of elements in a list, we can use Python’s built-in sum() function as shown in the following example:

                                                          Example

                                                          # creating a list  
                                                          
                                                          lst_one = [15, 61, 23, 6, 87, 5, 93]  
                                                          
                                                          print("Given List:", lst_one)  
                                                          
                                                            
                                                          
                                                          # finding sum of the elements in the list  
                                                          
                                                          print("Sum of the Elements in the list:", sum(lst_one))

                                                          Output:

                                                          Given List: [15, 61, 23, 6, 87, 5, 93]
                                                          Sum of the Elements in the list: 290
                                                          

                                                          Explanation:

                                                          In the above example, we have created a list. We then used the sum() function to calculate the sum of the elements in the given list.

                                                          Conclusion

                                                          Python lists provide a versatile way to handle multiple data items. With functionalities like appending, inserting, updating, and iterating, lists form the backbone of many Python programs. Mastering lists is essential for efficient programming in Python.

                                                        • Context Manager in Python

                                                          The Context Manager is an object in Python that ensures the resources are properly used in the block of code and automatically frees the resources, which improves efficiency and clean code. It lets the user manage any resource using __enter__ and __exit__.

                                                          In this tutorial, we will learn about “Context Manager” in Python, and we will also see how it is helpful in managing resources, file descriptors, and database connections.

                                                          Managing Resources

                                                          Managing the resources is one of the most important parts of the Context Manager. It allows the resources to be used more efficiently. The users use resources like file operations or database connections, which are very common in any programming language.

                                                          But all these resources have a limit. Therefore, the main problem is to make sure these resources will be released after usage.

                                                          Because if they are not released, this could lead to resource leakage, which may cause either a slowdown in the system or a crash. If the machine is set up in the system of users, which can automatically tear down the resources, it can be very helpful. In Python, users can achieve this by using context managers, which are used for facilitating the proper handling of resources. The most popular way of performing file operations is by using the “with” keyword in Python.

                                                          Python Example to Manage Resources

                                                          Let us take an example to demonstrate how to manage resources in Python.

                                                          with open("text_file.txt") as file:       
                                                              data = file.read()    

                                                          Let’s see an example of file management. When a file is opened, the file descriptors will be consumed, which is a limited resource. The process can open only a limited number of files at a time.

                                                          Another Example to demonstrate Manage Resources

                                                          Let us take another example to demonstrate how to manage resources in Python.

                                                          file_descriptors = []    
                                                          for Y in range(10000):    
                                                              file_descriptors.append( open ('test_file.txt', 'w'))    

                                                          Output:

                                                          OSError Traceback (most recent call last)
                                                          in
                                                          1 file_descriptors = []
                                                          2 for Y in range(10000):
                                                          ----> 3 file_descriptors.append( open ('test_file.txt', 'w'))
                                                          OSError: [Errno 24] Too many open files: 'test_file.txt'
                                                          

                                                          Explanation

                                                          The above example is the case of the file descriptor leakage. An error occurred saying, “Too many open files”. This has happened because there are so many open files, and they are not closed. There may be a chance that the users may have forgotten to close the open files.

                                                          How to Manage Resources using Context Manager?

                                                          It is tough to close a file in all the places if the block of the program raises an exception or has any complex algorithm with numerous return paths.

                                                          Most of the time, users use “try-except-finally” in other programming languages while working with the file to make sure that the file resource is closed after usage, even if there is an exception. But in Python, they can use “Context Manager” for managing resources. The users can use the “with” keyword. When it gets evaluated, it will result in an object that can perform context management. We can write context managers by using classes or functions with decorators.

                                                          How to Create a Context Manager?

                                                          When the user creates a context manager, they need to make sure that the class has the following methods: __enter__() and __exit__().

                                                          • The __enter__() method will return the resource that has to be managed.
                                                          • The __exit__() method will not return anything but perform the clean-up operations.

                                                          Let’s see an example to understand it in a better way:

                                                          First, we will create a simple class named “context_manager” for understanding the basic structure of creating a context manager by using the class method.

                                                          Python Example to Create a Context Manager

                                                          Let us take an example to demonstrate how to create a context manager in Python.

                                                          class context_manager():    
                                                              def __init__(self):    
                                                                  print ("The 'init' method is called")              
                                                              def __enter__(self):    
                                                                  print ("The 'enter' method is called")    
                                                                  return self          
                                                              def __exit__(self, exc_type, exc_value, exc_traceback):    
                                                                  print ("The 'exit' method is called")    
                                                          with context_manager() as manager:    
                                                              print ("The 'with' statement is a block")    

                                                          Output

                                                          The 'init' method is called
                                                          The 'enter' method is called
                                                          The 'with' statement is a block
                                                          The 'exit' method is called
                                                          

                                                          Explanation

                                                          In the above code, we have created the “context_manager” object. That is assigned to the variable after the “as” keyword, that is, manager. After running the program, the following methods got executed in the sequence:

                                                          • __int__()
                                                          • __enter__()
                                                          • Body of statement, which is the code inside the “with” statement block.
                                                          • __exit__(), In this method, the parameters are used for managing the exceptions.

                                                          File Management by using Context Manager

                                                          Now, we will apply the above concept for creating the class, which can help in file resource management. The “file_manager” class will help open the file, read or write content, and then close the file.

                                                          class file_manager():    
                                                              def __init__(self, file_name, mode):    
                                                                  self.filename = file_name    
                                                                  self.mode = mode    
                                                                  self.file = None              
                                                              def __enter__(self):    
                                                                  self.file = open(self.filename, self.mode)    
                                                                  return self.file          
                                                              def __exit__(self, exc_type, exc_value, exc_traceback):    
                                                                  self.file.close()      
                                                          # At last, load the file     
                                                          with file_manager('test_file.txt', 'w') as file:    
                                                              file.write( )      
                                                          print (file.closed)    

                                                          Output:

                                                          True
                                                          

                                                          Performing File Management using Context Manager and “with” Statement?

                                                          After the user executes the “with” statement block, the operations will get executed in the following sequence:

                                                          • A “file_manager” object will be created with “text_file.txt” as the file name, and “w” (write) as the mode when the __init__() method will be executed.
                                                          • The __enter__() method will open the “text_file.txt” in write mode and return the “file_manager” object to the variable “file”.
                                                          • The text “TpointTech” will be written into the file.
                                                          • The __exit__() method will take care of closing the file after exiting the “with” statement block, which is a teardown operation.
                                                          • When the “print (file.closed)” statement runs, the users will get the output “True” as the “file_manager” would have already closed the file, which otherwise would need to be explicitly done.

                                                          How to Manage the Database Connection using Context Manager?

                                                          Now, we will show how to create a simple database connection management system. There is a limit on the number of database connections at a time, just as with File descriptors. Therefore, we use a context manager, as it is helpful in managing the connections to the database, as the user might have forgotten to close the collection.

                                                          Install pymongo

                                                          To manage the database connection through the content manager, the user first has to install the “pymongo” library by using the following command:

                                                          !pip3 instal pymongo  

                                                          Python Example to Manage the Database Connectio using Context Manager

                                                          Let us take an example to demonstrate how to manage the database connection using context manage in Python.

                                                          from pymongo import MongoClient as moc  
                                                          class mongo_db_connection_manager():  
                                                              def __init__(self, host_name, port = '27017'):  
                                                                  self.hostname = host_name  
                                                                  self.port = port  
                                                                  self.connection = None   
                                                              def __enter__(self):  
                                                                  self.connection = moc(self.hostname, self.port)  
                                                                  return self    
                                                              def __exit__(self, exc_type, exc_value, exc_traceback):  
                                                                  self.connection.close()   
                                                          # Now, connect with a localhost  
                                                          with mongo_db_connection_manager('localhost', 27017) as mongo:  
                                                              collection_1 = mongo.connection.SampleDb.test  
                                                              data_1 = collection_1.find({'_id': 142})  
                                                              print (data_1.get(name))  

                                                          Output:

                                                          Test
                                                          

                                                          Explanation:

                                                          In the above code, after executing the “with” statement block, the following operations will happen in the sequence.

                                                          • The “mongo_db_connection_manager” object will be created with “localhost” as the “host_name” and the port is equal to “27017” when the __init__() method is executed.
                                                          • The __enter__() method will open the “mongodb” connection, and it will return the “mongo_db_connection_manager” object to the variable “mongo”.
                                                          • The “SampleDB” database will access the “test” connection, and the document with the “_id = 147” will be retrieved. It will print the name field of the document.
                                                          • The __exit__() method will take care of closing the file after exiting the “with” statement block, which is a teardown operation.

                                                          Conclusion

                                                          In this tutorial, we have discussed Context Manager in Python, how to create Context Manager, and how it can help in Resource Management, File management, and managing Database connections.