views:

653

answers:

7

What I mean is, I'm looking for really short code that returns the lower value. for example:

a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,3,4,5,6,7,8]
len(a) = 10
len(b) = 8
if (fill-this-in):
     print(lesser-value)

And I forgot to add that if b is lower than a, I want b returned - not len(b) - the variable b.

+3  A: 

min() should accomplish what you need

print(min(a,b))
vili
+6  A: 
print(min(a, b))
cschol
A: 

I don't know Python but for something like this I'd use a ternary operator.

print(length(a) < length(b) ? length(a) : length(b))

One thing to note about this that if they are equal it will print length(b)

Andrew G. Johnson
I didn't downvote you but, if you find yourself answering a python-tagged question starting with the immortal phrase "I don't know Python but ...", you may just want to think about not answering :-).
paxdiablo
A: 

Is the following what you want?

if len(a) < len(b):
    print a
else:
    print b

Alternatively, if you want to use the ternary operator like @Andrew G. Johnson:

print a if len(a) < len(b) else b

PS. Remember that Python does not use braces for its blocks, and that its ternary operator is different from C-like languages.

A. Rex
+16  A: 

You're not hugely clear about what you want, so some alternatives. Given the following two lists:

a = [1,2,3,4,5,6,7,8,9,10]
b = [1,2,3,4,5,6,7,8]

To print the shortest list, you can just do..

>>> print(min(a, b))
[1, 2, 3, 4, 5, 6, 7, 8]

To get the shortest length as an number, you can either min the len() of each list, or do len(min()) (both are identical, choose which ever you find most readable)..

>>> print(min( len(a), len(b) ))
# or..
>>> print(len( min(a, b) ))
8

To print the lowest value in either list, you can supply the list as a single argument to min()

>>> a.extend(b) # Appends b to a
>>> print a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8]
>>> print(min(a))
1

Finally, another possibility, the list that has the lowest values in total:

>>> max( sum(a), sum(b) )
55

To print the actual list with the highest sum(), you could either use the ternary operator, like..

>>> print a if sum(a) > sum(b) else b
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

..although I never really liked (or use) it, instead using the slight longer, regular if/else statements..

>>> if sum(a) > sum(b):
...     print a
... else:
...     print b
... 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
dbr
Upvoting 'cause it gives just about every possibility...
paxdiablo
+1 for thoroughness :) althouth the question should really be fixed
dF
+2  A: 

If the length of the list is what makes it lower (not its values), then you actually want:

min(a, b, key=len)

which is only incidentally equivalent to

min(a, b)

in the given example.

Coady
A: 

heads up, min(a, b, key=len) only works in python 2.5 and up I think.

(it's not working on my macbook with python 2.4, but my linux server with 2.5 is fine)

matt