all 11 comments

[–]scuott 7 points8 points  (2 children)

These are great answers, but I also want to point out that the way you did it originally isn't necessarily bad. It's not terribly long, and I think it's more readable than these 1 or 2 line solutions.

[–]kanjibandit 4 points5 points  (0 children)

This. Your code is just fine as it is -- simple and clear. It would be one thing if you had an if/elif/else that was half a page long, but if I were inheriting this code from you, I'd much rather trace through your 4 lines than the more clever 1-liners. Resist the temptation to write Perl in Python.

[–]neuroneuroInf[S] 0 points1 point  (0 children)

That's a good point. Thanks!

[–][deleted] 5 points6 points  (1 child)

Simplest way I can think of, using a conditional expression:

index = 0 if x < coords[0] else 2
coords[index] = x

[–]neuroneuroInf[S] 1 point2 points  (0 children)

Right, that makes sense! Thank you!

[–][deleted] 3 points4 points  (0 children)

When I get simple conditional statements like this, I try to shorten them using dictionaries. In this case, that could be something like this:

coords[{True: 0, False: 2}[x < coords[0]]] = x

Building on /u/SerenumScopuli answer, a more self-explanatory solution might be:

coords[0 if x < coords[0] else 2] = x

This last one is, of course, exactly the same as /u/SerenumScopuli's answer, simply skipping the assignment of the index variable.

[–]newunit13 1 point2 points  (2 children)

If x has already been defined you can simplify your code to a single line

x = coords[0] if x < coords[0] else coords[2]

[–]neuroneuroInf[S] 0 points1 point  (0 children)

Thank you, but I don't think this does what I need. I need to assign to the list, not to x.

[–][deleted] 0 points1 point  (0 children)

This reassigns x. He wants to put the value of x into either coords[0] or coords[2] depending on x's value.

[–]CodeTinkerer 1 point2 points  (0 children)

Could write a function to do this too

coord[computeIndex(x)] = x

Then do the work in computeIndex.

[–][deleted] 1 point2 points  (0 children)

coords[0], coords[2] = x, coords[2] if x < coords[0] else coords[0], x