Official website for Linux User & Developer
FOLLOW US ON:
Feb
12

Another ten essential Python tips

by Kunal Deo

To compliment our ‘ten essential Python tips for beginners’ and ‘ten more essential Python tips’ features, we’ve compiled yet another collection of ten gems to make your Python experience that much more worthwhile…

Disabling and enabling  garbage collection
Sometimes you may want to enable or disable the garbage collector at runtime. You can use the ‘gc’ module to enable or disable the garbage collection.

[Example]
>>> import gc
>>> gc.enable
<built-in function enable>
>>> gc.disable
<built-in function disable>

Using C-based modules for better performance
Many Python modules ship with counterpart C modules. Using these C modules will give a significant performance boost in complex applications.

[Example]
cPickle instead of Pickle, cStringIO instead of StringIO .

Calculating maximum, minimum and sum out of any list or iterable
You can use the following built-in functions.

max: Returns the largest element in the list.
min: Returns the smallest element in the list.
sum: This function returns the sum of all elements in the list. It accepts an optional second argument: the value to start with when summing (defaults to 0).

Representing fractional numbers
Fraction instance can be created using the following constructor:
Fraction([numerator [,denominator]])

Performing math operations
The ‘math’ module provides a plethora of mathematical functions. These work on integer and float numbers, except complex numbers. For complex numbers, a separate module is used, called ‘cmath’.
For example:

math.acos(x): Return arc cosine of x.
math.cos(x): Returns cosine of x.
math.factorial(x) : Returns x factorial.

Working with arrays
The ‘array’ module provides an efficient way to use arrays in your programs. The ‘array’ module defines the following type:

array(typecode [, initializer])

Once you have created an array object, say myarray, you can apply a bunch of methods to it. Here are a few important ones:

myarray.count(x): Returns the number of occurrences of x in a.
myarray.extend(x): Appends x at the end of the array.
myarray.reverse(): Reverse the order of the array.

Pages: 1 2
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.

    10 Comments »

    • gwb said:

      The example of removing dups from a list can also be done with set semantics:

      newlist = list(set(oldlist))

      Note that both this approach and the original one will destroy the order of the elements. If you want to preserve order, something like this would do it:

      def unique(list_):
      s = set()
      newl = []
      for x in list_:
      if x not in s:
      new.append(x)
      s.add(x)
      return newl

      You could even be tricksy with something like this:

      listset = set()
      newlist = list(x for x in oldlist if x not in listset and not listset.add(x))

      since set().add() returns None which is boolean False so “not set().add()” will always be true. However, this method involves redundant calls to set().add().

    • Tom K said:

      I think you want to complEment the other collections of tips, not complIment them.

    • paul said:

      Removing duplicates from lists can be done a lot easier with set. E.g.:

      >>> l = [1,2,2,3,4,4,5]
      >>> set(l)
      set([1, 2, 3, 4, 5])

    • Rick said:

      Since white space is significant in python, several of the code examples need to be cleaned up.

    • gwb said:

      the problem with the white space seems to be a problem of the site’s handling of data. Dunno if it supports pre-formatted tags. Let’s try:

      this
      is
      indented

    • gwb said:

      nope. didn’t work

    • Lawrence D’Oliveiro said:

      What do you think your “gc” example is achieving? It’s only referencing the functions, not calling them. I think you want empty parentheses “()” after each function name, to indicate you’re calling them.

    • Lawrence D’Oliveiro said:

      Removing duplicates: do it in one line using sets, not dictionaries:

      >>> l = (1, 2, 2, 3, 4)
      >>> l
      (1, 2, 2, 3, 4)
      >>> type(l)(set(l))
      (1, 2, 3, 4)
      >>> l = [3, 4, 3, 5, 6]
      >>> l
      [3, 4, 3, 5, 6]
      >>> type(l)(set(l))
      [3, 4, 5, 6]

    • anon said:

      just came across a link to few free python book. very useful for python beginners
      http://cmdlinetips.com/2011/09/free-python-books-online/

    Trackbacks

    What's your opinion?

    Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

    Be nice. Keep it clean. Stay on topic. No spam.

    * Required fields