Book Image

Python Unlocked

By : Arun Tigeraniya
Book Image

Python Unlocked

By: Arun Tigeraniya

Overview of this book

Python is a versatile programming language that can be used for a wide range of technical tasks—computation, statistics, data analysis, game development, and more. Though Python is easy to learn, it’s range of features means there are many aspects of it that even experienced Python developers don’t know about. Even if you’re confident with the basics, its logic and syntax, by digging deeper you can work much more effectively with Python – and get more from the language. Python Unlocked walks you through the most effective techniques and best practices for high performance Python programming - showing you how to make the most of the Python language. You’ll get to know objects and functions inside and out, and will learn how to use them to your advantage in your programming projects. You will also find out how to work with a range of design patterns including abstract factory, singleton, strategy pattern, all of which will help make programming with Python much more efficient. Finally, as the process of writing a program is never complete without testing it, you will learn to test threaded applications and run parallel tests. If you want the edge when it comes to Python, use this book to unlock the secrets of smarter Python programming.
Table of Contents (15 chapters)
Python Unlocked
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Utilities


Key 3: Easy iterations by comprehensions.

We have various syntax and utilities to iterate efficiently over iterators. Comprehensions work on iterator and provide results as another iterator. They are implemented in native C, and hence, they are faster than for loops.

We have list, dictionary, and set comprehensions, which produce list, dictionary, and set as result, respectively. Also, iterators avoid declaring extra variables that we need in a loop:

>>> ll = [ i+1 for i in range(10)]
>>> print(type(ll),ll)
<class 'list'> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ld = { i:'val'+str(i) for i in range(10) }
>>> print(type(ld),ld)
<class 'dict'> {0: 'val0', 1: 'val1', 2: 'val2', 3: 'val3', 4: 'val4', 5: 'val5', 6: 'val6', 7: 'val7', 8: 'val8', 9: 'val9'}
>>> ls = {i for i in range(10)}
>>> print(type(ls),ls)
<class 'set'> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Generator expression creates generators, which can be used to produce...