Python Data Structure | List, Tuple, Dict, Sets, Stack, Queue

Posted in

Python Data Structure | List, Tuple, Dict, Sets, Stack, Queue
vinaykhatri

Vinay Khatri
Last updated on December 21, 2024

    The interviewer will ask many questions about the data structure whenever you attend a tech job interview. This is because data structures are the basic concept of every programming language, and if you are not aware of these basics, you will face difficulty tackling the interview.

    This article will cover all the basics of Python data structure. In every programming language, you will find many data structures some of those are inbuilt data structures, and some are user-defined data structures. The user-defined data structures are those data structures that are defined by the user, such as stack, queue, linked list, etc., and the built-in data structures are arrays , lists, dictionaries, sets, tuples, etc.

    Though Python does not have a built-in concept of the array, you can import it using the NumPy package. In Python, you will find built-in data structures you have never seen in other programming languages, such as lists, dictionaries, tuples, and sets.

    What is a Data Structure?

    A data structure in simple language is “ data Structures are the different way of the programming languages of storing data on your computer.”

    Data structure matters a lot, and its primary concern is how to store data so it can be retrieved quickly and efficiently. It defines the relationship between the data and the different operations performed on the data. Data Structure can be classified in many ways, but the two main entities on which data structures are defined are Primitive data types and Non-primitive data types.

    Primitive Data Structures in Python In-built Non-Primitive Data Structure in Python
    Integers List
    Float Tuples
    String Dictionaries
    Boolean Sets

    In this article, we will discuss the Python In-built Non-Primitive Data Structure.

    List

    Definition - Lists are Python's most widely used data structure and look similar to Array. The main difference between an array and a list is that arrays are the collection of Homogeneous elements, whereas List is the collection of homogeneous and heterogeneous elements. If we go for a more specific definition of the list, this could be that a list is a collection of heterogeneous elements.

    In Python, the bracket plays an important role when you define a list. All elements should be inside the square brackets to declare a list. As with arrays, on the list, we use indexing to retrieve a value. We can pass the negative index to reverse the list in the list.

    Syntax

    List1= [ 1 ,"hello", "world" ,True ]
    List2 =list(range(10))
    print(List1)
    print(List2)
    print(List1[0]) # Indexing
    print(List2[2:6]) # list slicing
    print(List1[-2]) #Negetive Indexing

    Output

    [1, 'hello', 'world', True]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    1
    [2, 3, 4, 5]
    world

    Various methods can be applied to a list. Some of the most important methods are:

    • append()
    • extend()
    • insert()
    • remove()
    • index()
    • count()
    • pop()
    • reverse()
    • sort()
    • copy()
    • clear()
    • any()
    • all()
    • ascii()
    • bool()
    • enumerate()
    • filter()
    • iter()
    • list()
    • len()
    • max()
    • min()
    • map()
    • reversed()
    • slice()
    • sorted()
    • sum()
    • zip()

    Dictionaries

    Dictionaries are the unordered key: value pairs data structure in Python. Many programming languages have the concept of the associative array, which looks like dictionaries.

    In dictionaries, each key is associated with a value, and the keys are immutable and unique, but the value can be changed. To define dictionaries, we declare a pair of keys and values, and they should be separated by a : (colon) after defining a pair of keys and values, use (comma) to define the next key: value pair. Dictionaries use curly braces to signify the key and their associative values.

    Syntax

    dict_1= { "key1":"value1" , "key2":"value2", "key3":"value3" , "key4":"value4"}
    print(dict_1)

    Output

    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
    

    As in the above code, you can see that the output of the code is not in the sequence in which it had been declared; this is because dictionaries are the unordered data structure. As a like list, dictionaries also use indexing to call the values, but in dictionaries, we use keys to grab their corresponding values.

    # Syntax to grab the value using index or key.

    Dic={1:2, 3:4 ,'hello': 'world'}
    print(Dic['hello'])

    #Output

    'world'
    
    

    Dictionaries methods

    • clear()
    • copy()
    • fromkeys()
    • get()
    • items()
    • keys()
    • popitem()
    • setdefault()
    • pop()
    • values()
    • update()
    • any()
    • all()
    • ascii()
    • bool()
    • dict()
    • enumerate()
    • filter()
    • iter()
    • len()
    • max()
    • min()
    • map()
    • sorted()
    • sum()
    • zip()

    Tuple

    A tuple is similar to a list but has some differences. The main difference is that tuples are immutable, and to declare the tuple, we use parenthesis () instead of sq. brackets []. The immutability of the tuples signifies that once an element inside the tuple and has been declared, it can not be reassigned.

    Syntax

    Tup=(1,2,3,4,5)
    print(Tup)
    print(Tup[2]) # as like list tuple uses indexing to grab the value.

    Output

    (1,2,3,4,5)
    
    3

    Why use Tuples?

    • Tuples are faster than lists.
    • Often, we prefer that data structure whose value cannot be manipulated.
    • Not to override the declared values by mistake.

    You can convert a list into a tuple by using the tuple() inbuilt function, it is the easiest and shortest way of conversion.

    Convert a list into a tuple

    li=[1,2,3,4]
    tu=tuple(li)
    print(type(tu))

    Output

    <class_ tuple>
    

    Tuples methods

    • count()
    • index()
    • any()
    • all()
    • ascii()
    • bool()
    • enumerate()
    • filter()
    • iter()
    • len()
    • max()
    • min()
    • map()
    • reversed()
    • slice()
    • sorted()
    • sum()
    • zip()

    Sets

    The definition of a set is “Sets are the collection of unique unordered elements” . The unique element state that all the elements in a set are different. Sets are similar to the list because the set is mutable and represented inside the sq. brackets the only difference is that in a set, you cannot store two same values.

    Syntax

    sets = {1,2,3,4,5,6}
    
    print(sets)

    Output

    {1, 2, 3, 4, 5, 6}

    In the above code, when we print the list, it prints all the elements, including the repetitive ones, but when we print set, it prints only all elements except the repetitive elements.

    Set methods

    • count()
    • index()
    • any()
    • all()
    • ascii()
    • bool()
    • symmetric_difference()
    • symmetric_difference_update()
    • union()
    • update()
    • issubset()
    • disjoint()
    • intersection_update()
    • discard()
    • enumerate()
    • filter()
    • iter()
    • len()
    • max()
    • min()
    • map()
    • reversed()
    • slice()
    • sorted()
    • sum()
    • zip()

    Leave a Comment on this Post

    0 Comments