• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Cool features of Python

Contents

  • Cool features of Python
    • Rapid, readable programming
      • Intuitive looping through lists
      • Arbitrary Integer size
      • Swich values of variables
      • Return more than one variable
      • Short initialisation
      • Chaining Comparisons
      • Enumeration
      • Named String formatting
      • any() and all()
    • Testing and Documentation
      • Doctest
      • Sphinx
    • The Rest
      • Lists and Generators
      • for ... else
      • Step through lists
      • Dynamically add properties to objects and classes
      • Imaginary numbers
    • Read also

A friend wanted to know why I enjoy programming in Python so much more than programming in other languages. So I will describe some special features of Python which make it much easier to quickly implement algorithms.

I also made drafts how the tasks would be solved in most programming languages. When I say most, I mean most languages that are widely spread (so C/C++/Java is much more important than almost any other languages combined). I know that those tasks would be solved completely different in functional programming languages.

Rapid, readable programming

Intuitive looping through lists

You can loop through every list-like datastructure like this:

for element in list:
    print(element)

Arbitrary Integer size

Description: Print the sum of the digits of \(2^{100000}\). Java:

import java.math.BigInteger;

public class test {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("2");
        a = a.pow(100000);
        int sum = 0;
        for (int i=0; i < a.toString().length(); i++) {
            sum += a.toString().charAt(i);
        }
        System.out.println(sum);
    }
}

Python: (was much faster in both computation and programming time!)

big = 2 ** 100000
sumOfDigits = 0
for digit in str(big):
    sumOfDigits += int(digit)

print(sumOfDigits)

Python has no need for a special class as it has arbitrary length integers (see source)

Swich values of variables

Description: You want to make sure, that variable a is smaller than b (\(a < b\)). Most languages:

tmp = a
a = min(a, b)
b = max(tmp, b)

Python:

a, b = min(a, b), max(a, b)

Return more than one variable

Description: Evaluate \(f: \mathbb{R}^2 \rightarrow \mathbb{R}^3, f(x, y) := (x^2, y^2, x+y)\) Most languages:

double function(double x, double y) {
  double returnValues[3];
  returnValues[0] = x*x;
  returnValues[1] = y*y;
  returnValues[2] = x + y;
  return returnValues;
}

double values[3] = function(4, 5);
printf("Part 1: %.2f", values[0]);
printf("Part 3: %.2f", values[2]);

Python:

def function(x, y):
    return (x * x, y * y, x + y)


a, b, c = function(4, 5)
print("Part 1: %.2f" % a)
print("Part 3: %.2f" % b)

This is called "Argument Unpacking". In fact it does return only one variable (a tuple), but it creating the tuple is so easy that it does not feel like creating another variable.

Short initialisation

Description: Get a string representation of a list from the standard library Java:

import java.util.LinkedList;
import java.util.List;

public class test {
    public static void main(String[] args) {
        List<Integer> myList = new LinkedList<Integer>();
        myList.add(1);
        myList.add(3);
        myList.add(3);
        myList.add(7);
        System.out.println(myList);
    }
}

Python:

myList = [1, 3, 3, 7]
print(myList)

Both get the same result.

Chaining Comparisons

Description: You would like to check if \(x \in [-5, 42]\). Most languages:

if (-5 <= x &amp;&amp; x <= 42)

Python:

if -5 <= x <= 42:
    pass

Enumeration

Description: You have a list and you would like to print it, prefixed with the index in the list. Java:

List myList = (List initialisation and assignment, multiple lines)
int i = 0;
for (int element : myList) {
    System.out.printf("%i: %i", i, element);
    i++;
}

Python:

myList = [1, 3, 3, 7]

for nr, element in enumerate(myList):
    print("%i: %i" % (nr, element))

Named String formatting

Python allows you to give parameters names:

print("The %(foo)s is %(bar)i." % {"foo": "answer", "bar": 42})

any() and all()

Description: You have a very long list and you want to know, if a prime is in this list. Most languages:

List myList = (List initialisation and assignment of many values)
boolean isPrimePresent = false;
for (int element : myList) {
    if (isPrime(element)) {
        isPrimePresent = true;
        break;
    }
}

if (!isPrimePresent) {
    System.out.println("The list did not containe a prime.");
}

Python:

myList = [4, 4, 9, 12]

if not any(isPrime(x) for x in myList):
    print("The list did not contain a prime")

See also: StackOverflow answer from steveha.

Testing and Documentation

Doctest

You can write Documentation and Unit-Tests at the same time! Take a look at doctest — Test interactive Python examples.

Sphinx

Documentation can be generated from partially docstrings, partially rst files with Sphinx. It can be uploaded to pythonhosted.org just like neurolab did it (see also sphinx).

The Rest

Lists and Generators

I already wrote an article about Python Lists and Python Generators. I love Pythons lists ☺

for ... else

Description: You have a very long list and you want to know, if a prime is in this list. Most languages:

List myList = (List initialisation and assignment of many values)
boolean isPrimePresent = false;
for (int element : myList) {
    if (isPrime(element)) {
        isPrimePresent = true;
        break;
    }
}

if (!isPrimePresent) {
    System.out.println("The list did not containe a prime.");
}

Python:

myList = [1, 3, 3, 7]

for element in myList:
    if isPrime(element):
        break
else:
    print("The list did not containe a prime.")

Step through lists

Description: Print only every n-th element of an iterable.

for element in myList[::n]:
    print(elemenet)

Dynamically add properties to objects and classes

class Node(object):
    value = 3


a = Node()
b = Node()

print(a.value)

""" colorize the node! """
# print(a.color) ==> AttributeError

# thats ok, although the object originally had no attribute "color"
a.color = "white"
print(a.color)

# You can even add a property to the class
Node.special = "here is it"
print(b.special)

Imaginary numbers

Python directly supports usage of imaginary numbers:

(2j + 1) ** 2

Output: (-3+4j)

Read also

An Informal Introduction to Python


Published

Jun 8, 2012
by Martin Thoma

Category

Code

Tags

  • Programming 52
  • Python 141

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor