Python 3 – List comprehensions by examples - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Tuesday, August 7, 2018

Python 3 – List comprehensions by examples

In the post Using lists with Python 3 I explained something about lists in Python, however, since Python is very slow in FOR-LOOPS, to generate lists Python supports a concept named "list comprehensions". "list comprehensions" can be used to construct lists in a very natural and easy way, like a mathematician is used to do. For example:NEWLIST_LOOP = [] for counter in range(10): NEWLIST_LOOP.append(counter)The above piece of code generates this list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], using list comprehensions the same list can be generated with the following line of code:NEWLIST_COMP = [x for x in range(10)]one line of code versus 3 lines of code…. List comprehensions advantages: Compact notation: From the example above we have already seen the first advantage, we could write less code. And, as any SW developer knows "less code means less bugs" Speed: Another effect on using LC is to have better performances, for example imagine you have a square matrix (10000×10000) and you want to flatten this matrix.


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


This article is related to

xAppSoftware News,list,list comprehensions,python

No comments:

Post a Comment