Category: Python Data Structures

  • Python Data Structures

    In Python, data structures are the building blocks used for organizing, processing, retrieving, and storing data so that it can be accessed more efficiently. Python is a high-level, object-oriented language that allows users to learn the fundamentals of data structures and their algorithms more simply.

    Data Structures in Python

    Python offers various data structures, such as:

    • List
    • Tuple
    • Set
    • Dictionary

    Let us discuss these data structures with examples:

    Lists

    Python Lists are used to store multiple items of different data types in a single variable. It works in the same manner as arrays, but with only one difference: in lists, not all the items need to be of the same data type.

    Lists are mutable (can be modified, deleted or replaced) and can contain duplicate items. A list works in the same way as an array in C, vectors in C++ or ArrayList in Java.

    Python List Example 

    Let us see a simple example showing how to create a list:

    Example

    # creating list  
    
    list_1 = ['Python App', 12, False, 1.6, 3e12]  
    
    print("List 1:", list_1)  
    
      
    
    # creating a nested list  
    
    list_2 = [['Learn', 'Python App'], 3, True, 'Hello', 1.69]  
    
    print("List 2:", list_2)

    Output:

    List 1: ['Python App', 12, False, 1.6, 3000000000000.0]
    List 2: [['Learn', 'Python App'], 3, True, 'Hello', 1.69]
    

    Explanation:

    In the above example, we have created a simple list using the square brackets ‘[]’. This list consists of different elements of data types. Similarly, we have created a nested list (a list within a list).

    Tuple

    Python Tuple is defined as a collection of objects. It works in a similar way like list with an only difference is that Tuples are immutable (which means once you create a tuple in Python, we cannot add, delete or modify and element in it). Just like a List, a Tuple can also contain elements of various types.

    In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.

    Python Tuple Example

    Here is a simple example to create a tuple.

    Example

    # creating tuple  
    
    tuple_1 = ('Python App', 19, True, 1.6, 5e3)  
    
    print("Tuple 1:", tuple_1)  
    
      
    
    # creating a nested tuple  
    
    tuple_2 = (('Hello', 'World'), 13, False, 'Python App', 6.9)  
    
    print("Tuple 2:", tuple_2)

    Output:

    Tuple 1: ('Python App', 19, True, 1.6, 5000.0)
    Tuple 2: (('Hello', 'World'), 13, False, 'Python App', 6.9)
    

    Explanation:

    In the above example, we have created a simple tuple using the parentheses ‘()’. This tuple consists of different elements of data types. Similarly, we have created a nested tuple (a tuple within a tuple).

    Set

    Python Set is a collection of unordered data used to store multiple elements in a single variable. Set is also mutable, which means once they create a set in Python, you cannot change or modify its elements.

    In Python sets, duplicity is not allowed; therefore, you cannot have two items with the same value, which helps eliminate duplicate entries. It is commonly used to include membership testing. Set uses the popular Hashing technique that permits operations like insertion, deletion, and traversal in O(1) time on average.

    Python Set Example

    Let us see a simple example showing how to create a set.

    Example

    # creating set  
    
    set_1 = {'hello', 'python app', 40, 21, 'hello', 19.2, False}  
    
    print("Set 1:", set_1)  
    
      
    
    # creating a set with a tuple an element  
    
    set_2 = {('learn', 'python app'), 10, 10, 'welcome', 13.6, True}  
    
    print("Set 2:", set_2)

    Output:

    Set 1: {False, 19.2, 'python app', 21, 'hello', 40}
    Set 2: {True, ('learn', 'python app'), 'welcome', 10, 13.6}
    

    Explanation:

    In the above example, we have created a set by enclosing some items with curly braces ‘{}’. Here, we can observe that the duplicate elements are eliminated from the set. Moreover, we can observed that the elements in the set are not ordered. We have created another set containing a tuple, an immutable sequence.

    Dictionary

    Python Dictionary is used to store data values key: value pair. It’s different from lists as it is ordered and changeable, and it doesn’t contain any duplicate elements. The values provided can be of any data type and may even contain duplicate data; however, the keys are immutable and should not contain duplicate values.

    In the Dictionary, indexing is done using keys. They internally use the concept of hashing and are of any hashable type (which means an object that can never change, like strings, numbers, tuples, etc.)

    Python Dictionary Example

    Let us see a simple example to create a dictionary.

    Example

    # creating dictionary  
    
    dict_1 = {  
    
        'name': 'Johnson',  
    
        'age' : 19,  
    
        'profession' : 'Software Developer',  
    
        'company' : 'python app',  
    
        'age' : 24  
    
              }  
    
    print("Dictionary 1:", dict_1)  
    
      
    
    # creating a nested dictionary  
    
    dict_2 = {  
    
        'name': 'Sachin',  
    
        'dob' : {  
    
            'date': 11,  
    
            'month': 'March',  
    
            'year': 1999  
    
        },  
    
        'profession' : 'Web Developer',  
    
        'company' : 'python app'  
    
        }  
    
    print("Dictionary 2:", dict_2)

    Output:

    Dictionary 1: {'name': 'Johnson', 'age': 24, 'profession': 'Software Developer', 'company': 'python app'}
    Dictionary 2: {'name': 'Sachin', 'dob': {'date': 11, 'month': 'March', 'year': 1999}, 'profession': 'Web Developer', 'company': 'Tpoint Tech'}
    

    Explanation:

    In the above example, we have created a dictionary by enclosing some ‘key: value’ pairs with curly braces ‘{}’. Here, we can see key ‘age’ is repeated, therefore the value of the first key is updated with the second value of the key as dictionary only contains unique keys. We have also created a nested dictionary (a dictionary as a value of another dictionary).

    String

    Python String are arrays of bytes representing Unicode characters. For example, “pythonapp” is a string containing the sequence of characters – ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘a’, ‘p’, ‘p’.

    Python String Example

    Let’s understand this using an Example.

    Example

    # creating a string  
    
    my_str = "Learn Python App"  
    
    print("My String:", my_str)  
    
    print()  
    
      
    
    # performing operations on string  
    
    # given string  
    
    given_str = "Welcome to Learn Python App"  
    
    print("Given String:", given_str)  
    
    # printing results  
    
    print("Length of String:", len(given_str))  
    
    print("First Element of String:", given_str[0])  
    
    print("Last Element of String:", given_str[-1])  
    
    print("Fourth Element of String:", given_str[3])

    Output:

    My String: Learn Python App
    
    Given String: Welcome to Learn Python App
    Length of String: 22
    First Element of String: W
    Last Element of String: h
    Fourth Element of String: c
    

    Explanation:

    Here, we have created a string by enclosing a text with double quotation marks (“…”). We have also performed some operations on string, such as finding its length and also printing the different elements of the string.

    Collections Module

    Python Collection Module acts as a container that provides various in-built datatypes. Let’s understand them one by one.

    S. No.Data StructuresDescription
    1CountersThe Python counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.
    2OrderedDictPython OrderedDict is like a dictionary, with the only difference being that it to maintain the insertion order of keys in a dictionary.
    3DequePython Deque stands for Doubly Ended Queue. It is a list-like container used for accessing fast append and pop operations from both sides of the container. It supports both FIFO (First In, First Out) and LIFO (Last In, First Out) operations.
    4ChainMapPython ChainMap encapsulates different dictionaries into a single variable. It finds the key by searching all the dictionaries one by one unless the required value is found.
    5UserDictPython UserDict wraps all the dictionary objects. It acts as a container used by Python developer when they want to create their dictionary with some modified or new functionality.

    Conclusion

    In this tutorial, we explored the fundamental of data structures in Python that are used for data management and manipulation. From built-in structures like ListsTuplesDictionariesSets and Strings to more specialized structures like the Collections Module, each have its unique purpose in programming.

    Understanding these data structures are very useful as it improves the performance and clarity of your code. Applying data structures also strengthens your problem-solving capabilities in Python.

  • Python Data Structures

    In Python, data structures are the building blocks used for organizing, processing, retrieving, and storing data so that it can be accessed more efficiently. Python is a high-level, object-oriented language that allows users to learn the fundamentals of data structures and their algorithms more simply.

    Data Structures in Python

    Python offers various data structures, such as:

    • List
    • Tuple
    • Set
    • Dictionary

    Let us discuss these data structures with examples:

    Lists

    Python Lists are used to store multiple items of different data types in a single variable. It works in the same manner as arrays, but with only one difference: in lists, not all the items need to be of the same data type.

    Lists are mutable (can be modified, deleted or replaced) and can contain duplicate items. A list works in the same way as an array in C, vectors in C++ or ArrayList in Java.

    Python List Example 

    Let us see a simple example showing how to create a list:

    Example

    # creating list  
    
    list_1 = ['Learn', 12, False, 1.6, 3e12]  
    
    print("List 1:", list_1)  
    
      
    
    # creating a nested list  
    
    list_2 = [['Learn python app'], 3, True, 'Hello', 1.69]  
    
    print("List 2:", list_2)

    Output:

    List 1: ['python app', 12, False, 1.6, 3000000000000.0]
    List 2: [['Learn', 'python app'], 3, True, 'Hello', 1.69]
    

    Explanation:

    In the above example, we have created a simple list using the square brackets ‘[]’. This list consists of different elements of data types. Similarly, we have created a nested list (a list within a list).

    Tuple

    Python Tuple is defined as a collection of objects. It works in a similar way like list with an only difference is that Tuples are immutable (which means once you create a tuple in Python, we cannot add, delete or modify and element in it). Just like a List, a Tuple can also contain elements of various types.

    In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.

    Python Tuple Example

    Here is a simple example to create a tuple.

    Example

    # creating tuple  
    
    tuple_1 = ('python app', 19, True, 1.6, 5e3)  
    
    print("Tuple 1:", tuple_1)  
    
      
    
    # creating a nested tuple  
    
    tuple_2 = (('Hello', 'World'), 13, False, 'python app', 6.9)  
    
    print("Tuple 2:", tuple_2)

    Output:

    Tuple 1: ('python app', 19, True, 1.6, 5000.0)
    Tuple 2: (('Hello', 'World'), 13, False, 'python app', 6.9)

    Explanation:

    In the above example, we have created a simple tuple using the parentheses ‘()’. This tuple consists of different elements of data types. Similarly, we have created a nested tuple (a tuple within a tuple).

    Set

    Python Set is a collection of unordered data used to store multiple elements in a single variable. Set is also mutable, which means once they create a set in Python, you cannot change or modify its elements.

    In Python sets, duplicity is not allowed; therefore, you cannot have two items with the same value, which helps eliminate duplicate entries. It is commonly used to include membership testing. Set uses the popular Hashing technique that permits operations like insertion, deletion, and traversal in O(1) time on average.

    Python Set Example

    Let us see a simple example showing how to create a set.

    Example

    # creating set  
    
    set_1 = {'hello', 'python app', 40, 21, 'hello', 19.2, False}  
    
    print("Set 1:", set_1)  
    
      
    
    # creating a set with a tuple an element  
    
    set_2 = {('python app), 10, 10, 'welcome', 13.6, True}  
    
    print("Set 2:", set_2)

    Output:

    Set 1: {False, 19.2, 'python app', 21, 'hello', 40}
    Set 2: {True, ('tpoint', 'tech'), 'welcome', 10, 13.6}
    

    Explanation:

    In the above example, we have created a set by enclosing some items with curly braces ‘{}’. Here, we can observe that the duplicate elements are eliminated from the set. Moreover, we can observed that the elements in the set are not ordered. We have created another set containing a tuple, an immutable sequence.

    Dictionary

    Python Dictionary is used to store data values key: value pair. It’s different from lists as it is ordered and changeable, and it doesn’t contain any duplicate elements. The values provided can be of any data type and may even contain duplicate data; however, the keys are immutable and should not contain duplicate values.

    In the Dictionary, indexing is done using keys. They internally use the concept of hashing and are of any hashable type (which means an object that can never change, like strings, numbers, tuples, etc.)

    Python Dictionary Example

    Let us see a simple example to create a dictionary.

    Example

    # creating dictionary  
    
    dict_1 = {  
    
        'name': 'Johnson',  
    
        'age' : 19,  
    
        'profession' : 'Software Developer',  
    
        'company' : ' python app ',  
    
        'age' : 24  
    
              }  
    
    print("Dictionary 1:", dict_1)  
    
      
    
    # creating a nested dictionary  
    
    dict_2 = {  
    
        'name': 'Sachin',  
    
        'dob' : {  
    
            'date': 11,  
    
            'month': 'March',  
    
            'year': 1999  
    
        },  
    
        'profession' : 'Web Developer',  
    
        'company' : ' python app '  
    
        }  
    
    print("Dictionary 2:", dict_2)

    Output:

    Dictionary 1: {'name': 'Johnson', 'age': 24, 'profession': 'Software Developer', 'company': ' python app '}
    Dictionary 2: {'name': 'Sachin', 'dob': {'date': 11, 'month': 'March', 'year': 1999}, 'profession': 'Web Developer', 'company': ' python app '}
    

    Explanation:

    In the above example, we have created a dictionary by enclosing some ‘key: value’ pairs with curly braces ‘{}’. Here, we can see key ‘age’ is repeated, therefore the value of the first key is updated with the second value of the key as dictionary only contains unique keys. We have also created a nested dictionary (a dictionary as a value of another dictionary).

    String

    Python String are arrays of bytes representing Unicode characters. For example, “pythonapp” is a string containing the sequence of characters – ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘a’, ‘p, ‘p’, .

    Python String Example

    Let’s understand this using an Example.

    Example

    # creating a string  
    
    my_str = "Learn python app"  
    
    print("My String:", my_str)  
    
    print()  
    
      
    
    # performing operations on string  
    
    # given string  
    
    given_str = "Welcome to Learn python app  
    
    print("Given String:", given_str)  
    
    # printing results  
    
    print("Length of String:", len(given_str))  
    
    print("First Element of String:", given_str[0])  
    
    print("Last Element of String:", given_str[-1])  
    
    print("Fourth Element of String:", given_str[3])

    Output:

    My String: Learn python app
    
    Given String: Welcome to Learn python app
    Length of String: 22
    First Element of String: W
    Last Element of String: h
    Fourth Element of String: c
    

    Explanation:

    Here, we have created a string by enclosing a text with double quotation marks (“…”). We have also performed some operations on string, such as finding its length and also printing the different elements of the string.

    Collections Module

    Python Collection Module acts as a container that provides various in-built datatypes. Let’s understand them one by one.

    S. No.Data StructuresDescription
    1CountersThe Python counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable.
    2OrderedDictPython OrderedDict is like a dictionary, with the only difference being that it to maintain the insertion order of keys in a dictionary.
    3DequePython Deque stands for Doubly Ended Queue. It is a list-like container used for accessing fast append and pop operations from both sides of the container. It supports both FIFO (First In, First Out) and LIFO (Last In, First Out) operations.
    4ChainMapPython ChainMap encapsulates different dictionaries into a single variable. It finds the key by searching all the dictionaries one by one unless the required value is found.
    5UserDictPython UserDict wraps all the dictionary objects. It acts as a container used by Python developer when they want to create their dictionary with some modified or new functionality.

    Conclusion

    In this tutorial, we explored the fundamental of data structures in Python that are used for data management and manipulation. From built-in structures like ListsTuplesDictionariesSets and Strings to more specialized structures like the Collections Module, each have its unique purpose in programming.

    Understanding these data structures are very useful as it improves the performance and clarity of your code. Applying data structures also strengthens your problem-solving capabilities in Python.

  • Difference between Set and Dictionary in Python

    In Python, sets and dictionaries are the built-in data structures. A set is an unindexed and unordered collection that stores unique items. On the other hand, a dictionary is an unordered and indexed collection that stores data in ‘key-value’ pairs.

    Even though these two are used for storing data collections and share some similarities, they differ significantly in terms of structure, behavior, and applications.

    What is a Set in Python?

    In Python, A set is one of the four built-in data types used for storing collections, along with lists, tuples, and dictionaries. It is an unordered collection of unique items. Sets are considered mutable, which allows us to add or remove elements even after the set has been created.

    Sets are represented using curly braces {}, and the elements in the set are separated by commas. Usually, the set() function is used to generate an empty set, and {} is used to create an empty dictionary.

    Characteristics of a Set

    Here are some major characteristics of Python Set:

    • Unordered: Elements in a set do not have any particular order.
    • Mutable: Elements can be added or removed from a set after its creation (e.g., with add(), remove(), discard()).
    • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).

    Let us see an example to create sets in Python.

    Difference between Set and Dictionary in Python

    Python Set Example

    Let us see an example to create sets in Python.

    Example

    # creating the first set  
    # Isme "Learn python App" ek single element ki tarah treat hoga
    first_set = set(("Learn python App", 14, (1, 2, 3)))  
    
    # printing the first set  
    print(first_set)  
    
    # creating the second set  
    # set() function string ke har unique character ko alag-alag kar dega
    second_set = set("Learn python App")  
    
    # printing the second set  
    print(second_set)

    Output:

    {'Learn python App', (1, 2, 3), 14}
    {'p', 'n', 'y', 'e', 'h', 'o', 'r', 'L', 't', 'a', ' ', 'A'}

    What is a Dictionary in Python?

    Dictionary is a built-in data type used in Python 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 on the basis of the key.

    We generally use dictionaries to store related data, such as information associated with a particular object or entity, where it can easily be retrieved based on its key.

    Characteristics of a Dictionary

    Python dictionary comes up with several features, which are as follows:

    Difference between Set and Dictionary in Python
    • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+, the Order is maintained when inserting key-value pairs into the dictionary.
    • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
    • Unique Keys: A dictionary’s keys must be distinct (unique). If you attempt to insert a new value with a present key, the value that is present with the key will be replaced.
    • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.

    Python Dictionary Example

    Let us see an example to create dictionaries in Python.

    Example

    # simple program to create a dictionary in Python    
    
        
    
    # creating a dictionary    
    
    employee_data = {    
    
        'full_name': 'Irfan Khan',    
    
        'employee_id': 1023,    
    
        'department': 'IT'    
    
    }    
    
        
    
    # printing result    
    
    print("Employee Data:", employee_data)    
    
    print("Data Type:", type(employee_data))

    Output:

    Employee Data: {'full_name': 'Irfan Khan', 'employee_id': 1023, 'department': 'IT'}
    Data Type: <class 'dict'>

    Key Differences between Sets and Dictionaries

    The following are key differences between Sets and Dictionaries in Python:

    FeatureSetDictionary
    DefinitionSet is an unordered collection of unique elements.Dictionary is an ordered collection of key-value pairs.
    RepresentationCurly braces {}Curly braces {}, but with key-value pairs.
    OrderedNoYes (since Python 3.7)
    DuplicatesNot Allowed (only unique elements are stored)Not Allowed (keys must be unique; values can be duplicated)
    HashingHashable (if all elements within the set are hashable)Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
    MutableYes (elements can be added or removed)Yes (key: value pairs can be added, removed, or values modified)
    Use CaseStoring unique items, membership testing, set algebra operations, and removing duplicates.Mapping keys to values, efficient lookups by key, and representing structured or labelled data.
  • Difference between List, Set, Tuple, and Dictionary in Python

    List, Set, Tuple, and Dictionary are widely used data structures in Python. These data structures play a crucial role in maintaining and organizing data. In order to write efficient and effective Python code, one should know the key differences between these data structures.

    What is a List?

    A list in Python is a built-in data structure that allows us to store multiple items in a single variable. Lists are one of the widely used data structures in Python because they are mutable, ordered, and can hold different types of elements.

    Lists offer a flexible way to handle collections of data and come with many useful built-in methods. Lists are usually defined by enclosing the collection of elements separated by commas with square brackets [].

    Characteristics of a List

    Several characteristics of List in Python are as follows:

    • Ordered: Elements are stored in a particular order, and their position (index) is significant.
    • Mutable: One can modify the elements of a list once it’s created (e.g., using append(), insert(), remove(), pop()).
    • Allows Duplicates: There can be several instances of the same element in a list. This means that the element can be repeated n times.
    • Indexed Access: Elements are accessed by their index (which is generally an integer); the index of the first element is 0.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python List Example

    Let us see an example of a list in Python.

    Example

    # simple python program to create a list  
    
      
    
    # creating a list  
    
    lst_1 = [12, 'Learn python App', 3.61, True]  
    
      
    
    # printing the list  
    
    print("List :", lst_1)  
    
      
    
    # printing its data type  
    
    print(type(lst_1))

    Output:

    List : [12, 'Learn python App', 3.61, True]
    <class 'list'>

    Explanation:

    In this example, we have created a list by enclosing several elements of different data types with square brackets [].

    What is a Set?

    set is an unordered collection. It means that sets do not have any particular order for elements. Sets always store the distinct elements; they automatically eliminate any duplicate entries (if they are present in the set).

    Sets are represented using curly braces {}, and the elements in the set are separated by commas. Usually, the set() function is used to generate an empty set, and {} is used to create an empty dictionary.

    Characteristics of a Set

    Several characteristics of a set in Python are as follows:

    • Unordered: Elements in a set do not have any particular order.
    • Mutable: Elements can be added or removed from a set after its creation (e.g., with add(), remove(), discard()).
    • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Set Example

    The following is a simple example of a set in Python.

    Example

    # creating the first set  
    # Humne "TpointTech" ko "Learn python App" se replace kar diya hai
    first_set = set(("Learn python App", 14, (1, 2, 3)))  
    
    # printing the first set  
    print(first_set)  
    
      
    # creating the second set  
    # Yahan bhi string badal di gayi hai
    second_set = set("Learn python App")  
    
    # printing the second set  
    print(second_set)

    Output:

    {14, (1, 2, 3), 'Learn python App'}
    {' ', 'n', 'p', 'r', 'y', 't', 'A', 'h', 'o', 'e', 'L', 'a'}

    Explanation:

    In this example, we have created a set by enclosing several elements with curly braces {}.

    What is a Tuple?

    Tuple is a built-in data structure in Python used to store a collection of objects. It is quite similar to a list in terms of indexing, nesting, and repetition. But tuples are immutable, meaning we cannot change their elements once created. A tuple is created by enclosing the elements separated by commas within parentheses ().

    Characteristics of a Tuple

    Several characteristics of a Tuple  in Python are as follows:

    • Ordered: Items are stored in a definite order.
    • Immutable: Once a tuple is made, its items cannot be altered (no addition, deletion, or modification).
    • Supports Duplicates: A tuple may have more than one occurrence of the same element. It means that an element can be present n times.
    • Indexed Access: Access to elements is possible using their indexes, and the index starts with 0.
    • Used Usually with Fixed Collections: Tuples are used to represent collections of records that need not be changed in the future, e.g., coordinates or records.
    • Slightly Smaller than Lists: As tuples are immutable, they occupy less memory than lists.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Tuple Example

    We will now look at an example of a tuple in Python.

    Example

    # simple python program to create a tuple    
    
        
    
    # creating a tuple    
    
    tpl_1 = (19, 'Python', 7.8, True)    
    
        
    
    # printing the tuple    
    
    print("Tuple :", tpl_1)    
    
        
    
    # printing type of list    
    
    print(type(tpl_1))

    Output:

    Tuple : (19, 'Python', 7.8, True)
    <class 'tuple'>

    Explanation:

    In this example, we have created a set by enclosing several elements of different data types with curly braces ().

    What is a Dictionary?

    A Dictionary is a built-in data structure in Python that we use to store data in ‘key: value’ pairs. The dictionary is an unordered (since Python 3.7, insertion is ordered), mutable, and indexed collection where each key is unique and maps to the associated value. We generally use dictionaries to store related data, such as information associated with a particular object or entity, where it can easily be retrieved based on its key.

    Characteristics of a Dictionary

    Several chacteristics of a dictionary in Python are as follows:

    • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+, the Order is maintained when inserting key-value pairs into the dictionary.
    • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
    • Unique Keys: A dictionary’s keys must be distinct (unique). If you attempt to insert a new value with a present key, the value associated with the key will be replaced.
    • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.
    Difference between List, Set, Tuple, and Dictionary in Python

    Python Dictionary Example

    Here is a simple example of a dictionary in Python.

    Example

    # simple python program to create a dictionary  
    
      
    
    # creating a dictionary  
    
    dict_1 = {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}  
    
      
    
    # printing the dictionary  
    
    print("Dictionary :", dict_1)  
    
      
    
    # printing type of list  
    
    print(type(dict_1))

    Output:

    Dictionary : {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}
    <class 'dict'>

    Explanation:

    In this example, we have created a dictionary consisting of multiple ‘key: value’ pairs separated by commas and enclosed with curly braces {}.

    Key Differences between List, Set, Tuple, and Dictionary

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

    FeatureListSetTupleDictionary
    OrderedYesNoYesYes (since Python 3.7)
    Mutable (Container)Yes (elements can be added, removed, or modified)Yes (elements can be added or removed)No (elements cannot be changed after creation)Yes (key-value pairs can be added, removed, or values modified)
    Mutable (Elements)Yes (if the elements themselves are mutable)Yes (if the elements themselves are mutable)No (elements themselves cannot be changed if the tuple is immutable)Yes (values can be mutable; keys must be immutable)
    DuplicatesAllowedNot Allowed (only unique elements are stored)AllowedNot Allowed (keys must be unique; values can be duplicated)
    Indexing/AccessYes (integer-based index, starting from 0)No (elements are not ordered and cannot be accessed by index)Yes (integer-based index, starting from 0)Yes (key-based access; values are retrieved using their unique keys)
    HashingNot Hashable (cannot be used as keys in dictionaries or elements in sets)Hashable (if all elements within the set are hashable)Hashable (if all elements within the tuple are hashable)Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
    Syntax[item1, item2, …]{item1, item2, …} (empty set: set())(item1, item2, …) (single element tuple: (item1,)){key1: value1, key2: value2, …}
    Common Methodsappend(), extend(), insert(), remove(), pop(), index(), count(), sort(), reverse(), clear(), copy()add(), remove(), discard(), pop(), clear(), copy(), union(), intersection(), difference(), symmetric_difference()count(), index()get(), keys(), values(), items(), update()pop(), popitem(), clear(), copy(), setdefault()
    Memory OverheadGenerally higher than tuples for the same number of elements due to dynamic resizing capabilities.Can have overhead due to the need for hash table management to ensure uniqueness.Generally lower than lists for the same number of elements due to fixed size.Can have significant overhead due to the storage of both keys and values and the underlying hash table.
    Use CasesOrdered collections needing modification, maintaining order of insertion, and variable-length collections.Storing unique items, membership testing, set algebra operations, and removing duplicates.Representing fixed data structures, ensuring data integrity, used as keys in dictionaries (if elements are hashable), and returning multiple values.It maps the key to their values, efficient lookups by key and represents structured or labeled data.

    Conclusion

    We have learnt a lot about the differences between List, Set, Dictionary, and Tuple. The List, Tuple, and Dictionary(from Python version 3.7) are ordered, whereas the set is unordered. Similarly, the List, Set, and Dictionary are mutable. We have discussed each and every criterion in detail.

    We still feel that there’s a lot to come; features and objectives might change with upcoming Python versions.

  • Difference between List and Dictionary in Python

    Lists and dictionaries are two of the data types in Python that are known as collections of data. A list is an ordered collection that stores items using index numbers, making it ideal to manage data sequences. On the other hand, a dictionary stores data in key-value pairs, which allows fast and flexible access using unique keys.

    What is a List in Python?

    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. We can store any type of data in a list, including numbers, strings, or even a list.

    Difference between List and Dictionary in Python

    Characteristics of Lists:

    Several characteristics of Lists in Python are as follows:

    • 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 take an example to demonstrate the List in Python.

    Example

    # Creating a list    
    
    my_list = [14, 'banana', 8.2]    
    
      
    
    # printing the list      
    
    print("Initialized list:", my_list)      
    
    print("Data Type:", type(my_list))

    Output:

    Initialized list: [14, 'banana', 8.2]
    Data Type: <class 'list'>

    Explanation:

    In the following 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 Python Dictionary?

    Dictionary is a built-in data type used in Python 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 on the basis of the key.

    Difference between List and Dictionary in Python

    Characteristics of a Dictionary:

    Several characteristics of a Dictionary in Python are as follows:

    • Unordered: In this, A Dictionary does not maintain a particular order.
    • Mutable: In the Mutable data type, we can edit or make changes to the elements.
    • Keys-Value Pairs: The values in the Dictionary are stored as a collection of unique keys, and every key has its unique value.
    • 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.
    • Unique and Immutable Keys:The Dictionary keys are unique and immutable, such as strings, integers, and floats.
    • The Dictionary uses curly brackets ({})for declaration.

    Python Dictionary Example

    Let us take an example to demonstrate the Dictionary in Python.

    Example

    # Creating a dictionary  
    
    my_dict = {'name': 'John', 'age': 23, 'salary': 69000}  
    
      
    
    # printing the dictionary    
    
    print("Initialized dictionary:", my_dict)    
    
    print("Data Type:", type(my_dict))

    Output:

    Initialized dictionary: {'name': 'John', 'age': 23, 'salary': 69000}
    Data Type: <class 'dict'>
    

    Explanation:

    In this example, we have created a dictionary consisting of several key: value pairs separated by commas enclosed with the curly brackets {}.

    Key Differences between Lists and Dictionaries

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

    FeatureListDictionary
    DefinitionOrdered collection of itemsUnordered (insertion-ordered from Python 3.7+) key: value pairs
    Syntax[] (Square brackets){} (Curly braces)
    Data AccessBy index (for example, my_list[0])By key (for example, my_dict[‘a’])
    IndexingUses numeric index (0, 1, 2, …)Uses keys (can be strings, numbers, etc.)
    OrderingMaintains order of itemsMaintains insertion order (Python 3.7+)
    MutabilityMutable (can change items)Mutable (can add, remove, or change key: value pairs)
    DuplicatesAllows duplicate valuesKeys must be unique; values can be duplicated
    Best Used ForCollections of similar items (like a list of numbers)Related data pairs (like name: age, product: price, etc.)
    IterationIterates over valuesIterates over keys (or values/items using .values() or .items())
    Memory UsageLess than dictionary (generally)Slightly more due to key: value pair structure
    Search Time ComplexityO(n) slower for lookupsO(1) on average faster with hash table
    Nested StructuresCan contain other listsCan contain other dictionaries or mixed data types
  • 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.