List Comprehensions in Python

 It's 12:12 midnight, and after hovering through the tedious linode work and somehow passing the 3rd Checkpoint of my duo I thought of blogging. This topic list comprehensions is quite simple even in the first glance, the basic use of this is to make lists in one simple and succinct line, or we can say that instead of making a for loop or in the worst case if you have decided to make a big list on your own as an avocation. It is not that we can evade the looping process, but instead of a syntax like the below one:-

ls=[]

for i in range(10):

        ls.append(i+1)

We can make use of list comprehensions and can make the code compact by doing the same in just one line of code as shown below:-

ls1=[i+1 for i in range(10)]

These is just one of the useful functionalities of Python, we can also include maps inside of list comprehensions which is beneficial if we are making a new list from an existing one, and we wanna make some changes in the previous list like which all values should be there in the new list. 

Something like the below code:-

def main():

    lis=[1,2,3,4,5,6,7,8]

    ls=list(map(func,lis))

    print(*ls)

def func(n):

    return n*n

if __name__=="__main__":

    main()

The above code makes a new list ls which contains the squares of the number in the list lis, in a laconic, or to say in a PYTHONIC manner. :)

Comments

Popular Posts