10 basic Python usages that are easy to be ignored but should be mastered

Posted by maxime on Sat, 29 Jan 2022 17:57:01 +0100

I've been writing code all my life, but I've never mastered the essence of coding. In most cases, I use Visual Basic because I am most comfortable with VB. At the same time, I have a little knowledge of other languages (R, C, JavaScript, Applescript, Hypertext and BASIC learned in 1979). A few years ago, I decided to use Python only to improve my coding ability. Many wheels have been invented repeatedly in this process, but I don't mind because I enjoy solving problems. At the same time, more effective and python like solutions can sometimes be found. After a long time, there will be an epiphany, realizing that there is no need to deal with the problem in a difficult and lengthy way. Here are 10 Python usages. If I found them earlier, I might save a lot of time.

There are no list derivation and lambda functions. Although these two usages are Python style, efficient and cool, they are often encountered in StackOverflow or other places, so Python learners should know these two things. There are also no ternary operators, decorators, and generators, because I rarely use them.

There is another one in this article IPython notebook nbviewer edition.

1. Use Python 3 output in Python 2

Python 2 is not compatible with Python 3, which makes me wonder which version of Python to choose. Finally, I chose Python 2 because many of the libraries I needed were incompatible with Python 3.

But in fact, the biggest version differences in daily use are print and division behavior. Now I use import from future to import the output and division of Python 3 in the code of Python 2. Almost all the libraries I use now support Python 3, so I will migrate to Python 3 soon.

​
    mynumber = 5
     
    print "Python 2:"
    print "The number is %d" % (mynumber)
    print mynumber / 2,
    print mynumber // 2
     
    from __future__ import print_function
    from __future__ import division
     
    print('nPython 3:')
    print("The number is {}".format(mynumber))
    print(mynumber / 2, end=' ')
    print(mynumber // 2)
     
    Python 2:
    The number is 5
    2 2
     
    Python 3:
    The number is 5
    2.5 2
    

By the way, for those developers in C series who prefer brackets rather than indentation, here is another colored egg:

​
    from __future__ import braces
    File "", line 1
    from __future__ import braces
    SyntaxError: not a chance
    

2. enumerate(list)

Obviously, when iterating over the list, I should iterate over the elements and their indexes at the same time, but for a long time, I was embarrassed to use count variables or slices.

​
    mylist = ["It's", 'only', 'a', 'model']
     
    for index, item in enumerate(mylist):
      print(index, item)
     
    0 It's
    1 only
    2 a
    3 model
    

3. Chain comparison operator

Since I used static languages (in which the usage is ambiguous), I never put two comparison operators in one expression. In many languages, 4 > 3 > 2 returns False because 4

The result of 3 is Boolean, and true > 2 will result in False.

​
    mynumber = 3
     
    if 4 > mynumber > 2:
      print("Chained comparison operators work! n" * 3)
     
    Chained comparison operators work!
    Chained comparison operators work!
    Chained comparison operators work!
    

4. collections.Counter

Python's collection library looks the best. When calculating the number of elements in the set, StackOverflow finds the answer is to create an ordered dictionary, but I insist on using a code fragment to create a dictionary and calculate the frequency of elements in the result. Until one day, I found that I could use collections deque.

​
    from collections import Counter
    from random import randrange
    import pprint
     
    mycounter = Counter()
     
    for i in range(100):
      random_number = randrange(10)
      mycounter[random_number] += 1
     
    for i in range(10):
      print(i, mycounter[i])
     
    
​
    0 10
    1 10
    2 13
    3 6
    4 6
    5 11
    6 10
    7 14
    8 12
    9 8
    

5. Dictionary derivation

An important sign for Python developers is to understand list derivation, but in the end I found dictionary derivation also useful, especially when exchanging dictionary keys and values.

​
    my_phrase = ["No", "one", "expects", "the", "Spanish", "Inquisition"]
    my_dict = {key: value for value, key in enumerate(my_phrase)}
    print(my_dict)
    reversed_dict = {value: key for key, value in my_dict.items()}
    print(reversed_dict)
    
​
    {'Inquisition': 5, 'No': 0, 'expects': 2, 'one': 1, 'Spanish': 4, 'the': 3}
    {0: 'No', 1: 'one', 2: 'expects', 3: 'the', 4: 'Spanish', 5: 'Inquisition'}
    

6. Execute shell command with subprocess

Previously, I used the os library to call external commands to process files, but now I can perform complex commands such as ffmpeg in Python in an encoded manner for video editing.

(yes, both my customers and I use Windows. If you despise me for this, I will accept it generously!)

Note that using the os library to complete this specific command is better than using subprocess. I just want to have an order that everyone is familiar with. At the same time, generally speaking, it is a very bad idea to use the shell=True parameter in the subprocess. This parameter is only used here to place the output of the command in an IPython notebook unit. Don't use this parameter yourself!

​
    import subprocess
    output = subprocess.check_output('dir', shell=True)
    print(output)
    
​
    Volume in drive C is OS
    Volume Serial Number is [REDACTED]
    Directory of C:UsersDavidDocuments[REDACTED]
     
    2014-11-26 06:04 AM  <DIR>     .
    2014-11-26 06:04 AM  <DIR>     ..
    2014-11-23 11:47 AM  <DIR>     .git
    2014-11-26 06:06 AM  <DIR>     .ipynb_checkpoints
    2014-11-23 08:59 AM  <DIR>     CCCma
    2014-09-03 06:58 AM      19,450 colorbrewdict.py
    2014-09-03 06:58 AM      92,175 imagecompare.ipynb
    2014-11-23 08:41 AM  <DIR>     Japan_Earthquakes
    2014-09-03 06:58 AM       1,100 LICENSE
    2014-09-03 06:58 AM       5,263 monty_monte.ipynb
    2014-09-03 06:58 AM      31,082 pocket_tumblr_reddit_api.ipynb
    2014-11-26 06:04 AM       3,211 README.md
    2014-11-26 06:14 AM      19,898 top_10_python_idioms.ipynb
    2014-09-03 06:58 AM       5,813 tree_convert_mega_to_gexf.ipynb
    2014-09-03 06:58 AM       5,453 tree_convert_mega_to_json.ipynb
    2014-09-03 06:58 AM       1,211 tree_convert_newick_to_json.py
    2014-09-03 06:58 AM      55,970 weather_ML.ipynb
           11 File(s)    240,626 bytes
            6 Dir(s) 180,880,490,496 bytes free
    

7. Dictionary get() and iteritems() method

The get() method of the dictionary can set the default value. When the key found with get() does not exist, it is very useful to return the default value parameter in the method. As with enumerate() in the list, you can iterate over elements in the dictionary with key tuples.

​
    my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'}
     
    print(my_dict.get('airspeed velocity of an unladen swallow', 'African or European?n'))
     
    for key, value in my_dict.iteritems():
      print(key, value, sep=": ")
     
    African or European?
     
    quest: Holy Grail
    name: Lancelot
    favourite_color: blue
    

8. Tuple unpacking for exchanging elements

In VB, whenever you need to exchange two variables, you have to use a stupid temporary variable: c = a; a = b; b = c

​
    a = 'Spam'
    b = 'Eggs'
     
    print(a, b)
     
    a, b = b, a
     
    print(a, b)
     
    Spam Eggs
    Eggs Spam
    

9. Introspection tools

I know the dir() method. I thought the help() method and the? Magic commands are the same, but help() is more powerful.

​
    my_dict = {'That': 'an ex-parrot!'}
     
    help(my_dict)
    
​
    Help on dict object:
     
    class dict(object)
     | dict() -> new empty dictionary
     | dict(mapping) -> new dictionary initialized from a mapping object's
     | (key, value) pairs
     | dict(iterable) -> new dictionary initialized as if via:
     | d = {}
     | for k, v in iterable:
     | d[k] = v
     | dict(**kwargs) -> new dictionary initialized with the name=value pairs
     | in the keyword argument list. For example: dict(one=1, two=2)
     |
     | Methods defined here:
     |
     | __cmp__(...)
     | x.__cmp__(y) <==> cmp(x,y)
     |
     | __contains__(...)
     | D.__contains__(k) -> True if D has a key k, else False
     |
     | __delitem__(...)
     | x.__delitem__(y) <==> del x[y]
     |
     | __eq__(...)
     | x.__eq__(y) <==> x==y
     |
     
    [TRUNCATED FOR SPACE]
     
     |
     | update(...)
     | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
     | If E present and has a .keys() method, does: for k in E: D[k] = E[k]
     | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
     | In either case, this is followed by: for k in F: D[k] = F[k]
     |
     | values(...)
     | D.values() -> list of D's values
     |
     | viewitems(...)
     | D.viewitems() -> a set-like object providing a view on D's items
     |
     | viewkeys(...)
     | D.viewkeys() -> a set-like object providing a view on D's keys
     |
     | viewvalues(...)
     | D.viewvalues() -> an object providing a view on D's values
     |
     | ----------------------------------------------------------------------
     | Data and other attributes defined here:
     |
     | __hash__ = None
     |
     | __new__ =
     | T.__new__(S, ...) -> a new object with type S, a subtype of T
    

10. PEP-8 compatible string connection

PEP8 is a Python coding style guide. Apart from others, PEP8 requires that each line should not exceed 80 characters, and the excess part should be wrapped and indented.

You can wrap lines with backslashes, parentheses with commas "," () ", or an additional plus sign" + ". But for multiline strings, these solutions are not elegant enough. Python has a multiline string token, that is, three quotation marks, but this does not keep indentation after line breaks.

Another way is to use parentheses without commas. I don't know why this method works, but it works.

​
    my_long_text = ("We are no longer the knights who say Ni! "
            "We are now the knights who say ekki-ekki-"
            "ekki-p'tang-zoom-boing-z'nourrwringmm!")
    print(my_long_text)
    
​
    we are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!
    
    

 

Topics: Python Data Mining