Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two adjacent lists in python

I found this code example, which I think is very well written, but I'm having trouble understanding why part of it works.

The code searches for the longest word in a string:

def LongestWord(str):
    ''.join(map(lambda x: [' ',x][x.isalnum()], str)).split()

I have no idea how [' ',x][x.isalnum()] works. Does this construction have a name?

like image 775
New Avatar asked Feb 21 '26 15:02

New


2 Answers

break it into 2 parts...

[' ', x]

builds a list of 2 elements. re-write as:

lst = [' ', x]
lst[x.isalnum()]

Now we see that the second brackets are to index the list created by the first brackets. Since str.isalnum() returns a boolean (True or False) and since booleans behave like integers in python (True -> 1, False -> 0), then the construction just picks one of the two elements in the list.

Note that these days (python2.5 and later), it is more idiomatic (and probably more efficient) to use a conditional expression:

lambda x: x if x.isalnum() else ' '
like image 74
mgilson Avatar answered Feb 24 '26 11:02

mgilson


The key to understanding this code is to know that boolean values can be used to index lists.

['a','b'][True] # produces 'b'
['a','b'][False] # produces 'a'

so the code

[' ',x][x.isalnum()]

will produce x if x is alpha-numeric otherwise it will produce ' '

like image 22
Andrew Johnson Avatar answered Feb 24 '26 10:02

Andrew Johnson