Signup/Sign In

Some Useful Concepts that Every Python Programmer Should Know

Posted in Programming   LAST UPDATED: SEPTEMBER 14, 2021

    In this article, we are going to cover some important topics/commands that you must know as a Python Programmer. This article will surely help you in enhancing your coding skills in Python.

    Although every concept we discuss here is present in Python's official documentation but we try to organize the information in a better way. Also, most of us don't find reading the documentation easy.

    Let's see the topics which we will be covering in this article.

    Table of Contents:

    1. Python Versions
    2. Python Shell
    3. os and sys Modules
    4. List Comprehensions
    5. Slicing
    6. Dictionaries and Sets
    7. Copying

    If you are just starting with Python programming language, we would like to recommend you this amazing complete Python Language Tutorial for Beginners.

    1. Python Versions

    Although it's not something that is used while writing programs, still you must know the version of Python language you are working with. Also, you have to know what they change in the versions of Python.

    Python versions are numbered as (x.y.z), where x, y, z are numbers which represent important changes in the language. For example, going from 2.7.x to 2.7.y represents small bugs and fixes in the language whereas from 2.xx to 3.xx represents some significant changes in the syntax.

    Although you can use the backward features of Python in the new versions, it's recommended to check the documentation to confirm whether a certain feature is backward compatible or not. You can easily check what changes have been made in various versions by going to the Python documentation.

    If you want to check the current version of your Python programming language, run the following command in command line:

    python --version


    2. Python Shell

    One of the greatest features of Python is that it has a built-in shell to run the code. It is known as an Interactive Mode.

    To enter into the interactive mode type python in the command line. The command will take you into the interactive mode.

    >>>

    Let's see some examples:

    >>> a = 5
    >>> b = 6
    >>> a + b  # executing some operation on variables a, b
    11
    
    >>> list(range(10))
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> _
    
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> _.append(10)
    
    >>> _
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    >>> l = _
    >>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    _ is a special variable in Python. It stores the calculated value from the last command in the interactive mode. You can use it as a variable in both interactive and script mode.


    3. os and sys Modules

    Both os and sys modules are very useful. They have some important methods which can be used in many situations in python programs.

    The os module provides a way of using system dependent functionalities.

    Take a look at all the methods of the os module by using dir() method. Run the following code to get all the methods of the os module:

    import os
    
    print(dir(os))

    Output:

    ['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', ... ]

    You can inspect all the methods to know their usage by using help() method.

    sys Module: This module holds system-specific parameters and functions. This module provides access to some variables used or maintained by the interpreter and to functions that interact directly with the interpreter.

    Apply the dir() method and help() methods to get all methods and description of the sys module.

    Run the following code:

    import sys
    
    print(dir(sys))

    Output:

    ['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', ... ]


    4. List comprehensions

    List comprehension is a better way for creating lists in Python. Most of the python programmers love this concept because of its beauty and simplicity in the syntax.

    Following is the syntax for list comprehension:

    variable_name = [iterator_variable for iterator_variable in range(values)]

    The above code is a basic example of list comprehension. You can also use conditions and nested loops in the list comprehensions.

    Let's see some more examples:

    # to create a simple list
    
    l = [i for i in range(10)]
    
    print(l) # it will print a list containing the numbers from 0 to 9

    Output:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    Now, we are going to learn how to use conditions inside the list comprehensions.

    # below code will create a list containing all the even numbers from 0 to 9
    
    evens = [i for i in range(10) if i % 2 == 0]
    
    print(evens)

    Output:

    [0, 2, 4, 6, 8]

    Now, let's see how to use the nested loops inside list comprehensions.

    # below code will create a list containing 3 sublists which contains 0s
    
    l = [[0 for i in range(3) for i in range(3)]
    
    print(l)

    Output:

    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

    The technique of List comprehension can also be used with dictionaries, sets, tuples etc.

    The above examples are basic when it comes to list comprehension. You can do a lot more with list comprehensions. Try to practice as much as possible for better understanding.


    5. Slicing

    Slicing is a process of taking out a part of any given data. You can perform slicing on strings, lists, tuples, etc., in python. Slicing is a convenient concept in python which h can be used to extract a part of any given data.

    The syntax of slicing in python is:

    variable_name[start : stop : step]

    where,

    start: start is the starting index

    stop: stop is the last index to stop slicing

    step: step is used to skip or jump while slicing. It helps to slice only even, odd, etc., places. The default value is 1.

    Let's see an example:

    >>> l = [i for i in range(10) if i % 2 == 0]
    >>> l
    [0, 2, 4, 6, 8]
    
    >>> l = [[0 for i in range(3)] for i in range(3)]
    >>> l
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    
    >>> l = [i for i in range(10)]
    >>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    >>> l[2:5]
    [2, 3, 4]
    
    >>> l[2:]
    [2, 3, 4, 5, 6, 7, 8, 9]
    
    >>> l[:5]
    [0, 1, 2, 3, 4]
    
    >>> l[0:9:2]
    [0, 2, 4, 6, 8]
    
    >>> l[1::2]
    [1, 3, 5, 7, 9]
    
    >>> l[::]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    >>> l[::-1]
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

    In the above interactive shell, you will see all the different ways in which we can use slicing. In the example above we have performed slicing on list, but the same will apply for other iterators like Strings, Tuples, etc.


    6. Dictionaries and Sets

    Dictionaries are made of key:value pairs, enclosed within curly brackets. Let's see the syntax:

    dict_name = {key1:value1, key2:value2}

    You can use string or int as the key. And you can access the dictionary values using the respective keys.

    See the below example:

    # creating a dictionary
    
    dictionary = { 1 : 2, 2 : 3, 3 : 4}
    
    # accessing the values using keys
    
    print(dictionary[1])
    
    print(dictionary[3])

    Output:

    2
    4

    Let's have another example with strings as keys in the dictionary:

    #creating a dictionary using strings as keys
    
    dictionary = {"john" : 21, "Silly" : 18, "Bob" : 24}
    
    print(dictionary['Bob'])
    
    # below code will add a key: value pair to the dictionary
    
    dictionary['Kane'] = 20
    
    print(dictionary)

    Output:

    24
    {'john': 21, 'Silly': 18, 'Bob': 24, 'Kane': 20}

    Sets are groups of distinct elements. It doesn't hold any duplicate values in it. You can create a set using { } braces. Let's see a few example to understand how to create sets.

    You can convert a set to list and vice versa using set() and list() methods.

    # creating a set
    
    # converting a list to set
    
    l = [1, 2, 3, 3]
    
    s = set(l) # this converts the list to set and removes the duplicate if it has any
    
    print(s)
    
    s1 = {1, 2, 3, 4, 4, 5}
    
    print(s1) # it prints the set which doesn't contain any duplicate value

    Output:

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


    7. Copying

    You can copy a list by simply assigning it to a new variable. But this type of copy is not deep copying which means when you will change the first list then the second list(formed by copying the first list) also changes automatically. See the example below:

    >>> list1 = [1, 2, 3, 4]
    >>> list2 = list1
    >>> list2.append(5)
    >>> list2
    [1, 2, 3, 4, 5]
    >>> list1
    [1, 2, 3, 4, 5]

    You will see that both are affected when you try to change one. How to avoid this?

    You can avoid this by using the copy() method. See the example below:

    >>> list1 = [1, 2, 3, 4]
    >>> list2 = list1.copy()
    >>> list2
    [1, 2, 3, 4]
    >>> list2.append(5)
    >>> list2
    [1, 2, 3, 4, 5]
    >>> list1
    [1, 2, 3, 4]

    Now, you can see that when we add a new element to list2, the original list is not affected. You can also use the methods of copy module to get the same results.


    End Note

    Hope you learned something new today. This is just a quick article to cover some important yet simple concepts which we tend to skip or miss while learning python programming language.

    If you have any doubts regarding this article, please mention them in the comment section.

    You may also like:

    Published by: hafeezulkareem
    Tags:PythonPython Programming
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS