Python Tricks

1. Access the last element in a non-empty array:

a = [1,2,3] 
>>> a[-1]
3
# Last element in a string
>>> a[-1:]
[3]
# access string or list removes last element
>>> a[:-1]
[1,2]
# empty list or string
a = []
>>> a[-1:]
[]
>>> a[-1]
IndexError: list index out of range

2. To see whether a list is empty:

a = []
result = "NO" if a else "YES"
>>> result
"YES"

3. Limit functions/classes to be exported:

__all__, It is a list of strings defining what symbols in a module will be exported when from import * is used on the module.

4. Access keys in a dictionary:

# Iterate keys in dictionary
foo = {"a":1, "b":2, "c":3}
>>> [i for i in foo]
["a", "b", "c"]
# This is equivalent to 
>>> [i for i in foo.keys()]
["a", "b", "c"]

5.Infinity floating point

>>> not_a_number = float('nan')
>>> not_a_number
nan

>>> neg_infinity = float('-inf')
>>> neg_infinity
-inf
>>> -100000 > neg_infinity
True

>>> positive_inf = float('inf')
>>> 100 < positive_inf
True

6.Load variable from string

# Suppose we are importing the list variable from rnn_data file.
variable_name = "rnn_data.input_dense_weights"
weights = eval(variable_name)

7. UTF-8 Encoding

In Python 2, if there are some non-ASCII characters (such as Chinese characters) in the Python script, the interpreter will complain about it. To slove it, we can:

  1. Use Python 3, as UTF-8 is the default source encoding in Python 3.
  2. In the source header, declare:
# -*- coding: utf-8 -*-

8. Swap two variables in Python:

left, right = right, left

The right-hand side is evaluated, a tuple of two elements id created in the memory. Then the left-hand side is evaluated, that is to say the tuple is assigned to the left-hand side. The tuple is unpacked in order to assign the variables.

https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python

Reference

https://www.geeksforgeeks.org/10-essential-python-tips-tricks-programmers/

http://www.siafoo.net/article/52

Python Reference and Copy:

https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list