Linux, programming, computers and life

September 7, 2006

Things to remember about python

Filed under: programming, python

My main programming language for a long time (more than 5 years) is C++. I still use it at work every day. Now, when i started to use python for several small (non work-related) projects, there’re several things which made me rewrite some code when i discovered them, since they are done differently in python and C++. In other words, some tips on python for C/C++ programmers and a reminder for me :)

  • when you need to know both element (in sequence) and it’s index use enumerate

          for index, element in enumerate([’a', ‘b’, ‘c’]): print ‘i: %d e: %s’ % (index, element)

  • when you need to iterate more than one sequence in parallel use zip

          for e, o in zip([2,4,6,8], (1,3,5,7)): print e, ‘ :: ‘, o

  • use xrange instead of range for performance
  • iterate sequences as much as possible instead of using elements index ([] operator). This way if you change your list to generator expression, it’ll still work
  • use in operator to verify whether something is in a sequence, i.e.:

          if 3 in [1, 2, 3]: print ‘OK’

Technorati Tags: , , ,

Comments »

The URI to TrackBack this entry is: http://linux4all.blogsome.com/2006/09/07/things-to-remember-about-python/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Get free blog up and running in minutes with Blogsome
Theme designed by Gary Rogers