Python Tricks

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

a = [1,2,3] 
>>> a[-1]
# Last element in a string
>>> a[-1:]
# access string or list removes last element
>>> a[:-1]
# 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

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

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

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

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.


Python Reference and Copy: