lambda in Python

In Python, lambda is a mechanism to create a small anonymous function. The function must take at least one parameter or more. The function body is restricted to a single expression. The lambda function can be passed anonymously to other functions that take a function as a parameter. Or it can be assigned a name and can be used just like a normal function, by calling by that name and passing it parameters.

# Syntax: lambda parameter(s): expression
lambda x: x     # Maps a parameter to itself
lambda x: x + 1 # Increments input parameter
lambda x: x * 2 # Doubles input

# Assign lambda a name
foo = lambda x: x * 2
foo( 10 )
# 20

For more info, see More Control Flow Tools.

Tried with: Python 3.2.2

About these ads

Conditional Expression in Python

Python does not have the ternary operator seen in C-like languages. Instead it has the conditional expression. It is of the form X if C else Y:

i = 99
x = True if 99 == i else False
# True

In X if C else Y, either or both of X and Y can themselves be conditional expressions:

i = 99
j = 42
x = ( list() if 42 == j else tuple() ) if 99 == i else False
# []

The conditional expression can be used as a cool and easy-to-read alternative to a chain of if-else statements:

# Peter Norvig's example in Udacity CS212
return (
    9 if (5, ) == counts else
    8 if straight and flush else
    7 if (4, 1) == counts else
    6 if (3, 2) == counts else
    5 if flush else
    4 if straight else
    3 if (3, 1, 1) == counts else
    2 if (2, 2, 1) == counts else
    1 if (2, 1, 1, 1) == counts else
    0)

For more info on conditional expressions, see Expressions and PEP 308.

Tried with: Python 3.2.2

max and min in Python

With multiple input arguments, max returns the maximum amongst them.

max( 33, 99, 45 )
# 99

With single argument, which must be an iterable, max returns the maximum item in the iterable.

a = ( 33, 99, 45 )
max( a )
# 99
max( "Gandhi" )
# 'n'

max also takes an optional ordering function through its key argument. This function will be called with each item and is expected to return a value that max can use for finding its maximum.

def myfoo( i ):
    if "a" == i: return 10
    if "b" == i: return 99
    if "c" == i: return 50
max( "abc" )
# 'c'
max( "abc", key=myfoo )
# 'b'

All of the above applies to the min function too.

For more information, see Built-in Functions.

Tried with: Python 3.2.2

assert in Python

i = 99

# assert expression
assert 99 == i

# assert expression, message
assert 99 == i, "This is printed when this assert fails"
assert 99 == i, "Value of i is {}, not 99".format( i )

When an assert statement fails, AssertionError exception is raised. If the assert statement has a message, that message is printed along with the AssertionError message.

Tried with: Python 3.2.2

Python: Creating a tuple

# Empty tuple
t = ()
t = tuple()

# Tuple with one item
t = (99,)
t = ("snake",)
t = tuple([99])
t = tuple(["snake"])

# Tuple with many items
t = (99,"snake")
t = tuple([99,"snake"])

# Tuple with nested items
t = ((99,100),"snake")

# Works in many places, *not* everywhere
t = 99,
t = 99, "snake"

Tried with: Python 3.2.2

Using list as queue in Python

The humble list can be used as a simple queue in Python.

q = []

for i in range( 0, 5 ):
    q.append( i ) # Add to back of queue

while q: # Queue not empty
    j = q.pop( 0 ) # Get from front of queue
    print( j )

# Output: 0 1 2 3 4

Note that popping the first item of a list is not optimal due to the way it is implemented. For large queues, using deque as queue is a much better option.

Tried with: Python 3.2.2

Ubuntu x86-64 CPU error on VirtualBox

Problem

Installing 64-bit Ubuntu on VirtualBox fails with this error:

This kernel requires an x86-64 CPU, but only detected an i686 CPU. Unable to boot – please use a kernel appropriate for your CPU.

Solution

First, make sure you have a 64-bit CPU. Second, make sure it has support for virtualization. If both of these are true, then it means that some of the virtualization features might be turned off. Reboot your PC, get into the BIOS setup and turn on all the virtualization features of your CPU. 64-bit Ubuntu should install without this error after that.

Tried with: Ubuntu 11.10 64-bit and VirtualBox 4.1.12 on a Intel Core 2 Duo E6550 CPU

DownThemAll!

If you use Firefox as your primary browser, then having a good download manager is a must. The built-in downloader of Firefox is all right, but there is much more a download manager can do to make your life easier.

I have been using the DownThemAll! addon as my download manager for a long time now. It is actually meant to download all or many of the content files on a webpage. But, I use it because it can accelerate downloads by downloading multiple pieces of the file at the same time. I can also use it to pause and restart downloads. It also displays some cool-looking graphs and detailed statistics while it downloads files.

[ The OneClick button on Save dialog ]

I also like to configure it so that it appears in the right-click context menu and in the Save dialog. In both of these places, it can be further configured as dTA OneClick, which means it starts downloading when I click it without asking me where and how to save it. The OneClick feature takes the settings from the previous download and runs with it. This saves me from going through one more dialog, which is quite useful if you always save files to the same directory.

Tried with: DownThemAll! 2.0.13