Archive for November 6, 2008

Python: understanding/reading list comprehensions

List comprehensions in Python can be tricky and hard to look at but once you know the secret, it will become very clear, for example, say we have a list:

a = [1, 2, 3, 4, 5]

And we want to make a second list out of this “b” with values of “a” plus 2, so we want to get this:

b = [3, 4, 5, 6, 7]

Now, the way to do this without using any fancy feature would be:

b = []
for item in a:
    b.append(item + 2)

To turn this into a list comprehension we will start like this:

b = [for item in a]

Now, we will have to add our “item + 2″ to the left side of the for loop so:

b = [item + 2 for item in a]

If you didn’t understand what happened, don’t worry, just keep reading.
Now, let’s look at another example, this time, we will try to understand a list comprehension that’s already written, a very simple one:

a = [1, 2, 3, 4, 5]
b = [x*x*x for x in a]

To read this, start form right to left:

for x in a: x*x*x

Internally, this will be translated to something like:

b = []
for x in a:
    b.append(x*x*x)

So the secret is to read from right to left.

If there should be a condition, it will come after the for loop so to increment all the items that are greater than 4 by 2:

b = [item + 2 for item in a if item > 4]

I hope this helps :)

Archived under Python Comments

Print without a new line or space in Python

Here is another little trick in Python; the print statement always inserts a line break after it prints your text, for example:

print "Hello"
print "Python"
print "!"

Will print:
Hello
Python
!

Now, you can fix the issue with the line break by inserting a comma after the print statement:

print "Hello",
print "Python",
print "!"

This will print:
Hello Python !

But the problem is that it will still insert a space after it prints the text, so to fix this you will have to use sys.stdout.write like this:

import sys
sys.stdout.write("Hello ")
sys.stdout.write("Python")
sys.stdout.write("!")

This will print:
Hello Python!

Have fun with Python :)

Archived under Python Comments (4)

__FILE__ equivalent in Python; get the path to current file in Python

Update:
There is __file__ in Python.

You could do this as suggested by some but I don’t know why:

import inspect
this_file = inspect.currentframe().f_code.co_filename

I hope this helps :)

Archived under Python Comments (4)