## Ordering a list in python

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

jgrocho
Posts: 6
Joined: Mon Apr 21, 2008 5:10 am UTC

### Ordering a list in python

Using python I want to create a list in a specific order. The following code demonstrates a first attempt at creating this order.

Code: Select all

max = 16
g = []
a = 0
b = size - 1
for x in range(max/2):
if a % 2 == 0:
g.append(b)
g.append(a)
else:
g.append(a)
g.append(b)
a += 1
b -= 1
print g

which produces

Code: Select all

[15, 0, 1, 14, 13, 2, 3, 12, 11, 4, 5, 10, 9, 6, 7, 8]

I was wondering if anyone has a simpler, more elegant method of doing such a thing. Also max will always be even so don't worry about odd cases.

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: Ordering a list in python

I think your method seems fine, it's straight-forward and easy to follow. You could do something like:

Code: Select all

max = 16
g = []
for x in range(max / 2):
a, b = x, max - x - 1
g += [b,a] if x % 2 == 0 else [a,b]
print g

It's less code but the guts are the same, I've just removed the unnecessary counters and condensed the append operations.

PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

### Re: Ordering a list in python

Here's a more obfuscated version. On the positive side, it is a list comprehension.

Code: Select all

max=16; m=max-1; print sum([i%2 and [i,m-i] or [m-i,i] for i in xrange(max//2)], [])

It's probably not a great idea to use max as a variable name, though, as it's a built-in function.

jgrocho
Posts: 6
Joined: Mon Apr 21, 2008 5:10 am UTC

### Re: Ordering a list in python

Thanks for the suggestion about not using max (I'm not actually using any of the variable names in my real script, I just needed some simple names). Both are great suggestions. I knew there was at least one way to make this code a little more elegant.

rog
Posts: 10
Joined: Fri May 21, 2010 5:13 am UTC

### Re: Ordering a list in python

I tried to come up with something using the sorted function, but no luck. I think your way is pretty good.
In the spirit of thefairest.info ... "More Betterer"

Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

### Re: Ordering a list in python

Code: Select all

[x/2 if (x/2^x)&1 else max-1-x/2 for x in range(max)]

If max is divisible by 4:

Code: Select all

sum(zip(range(max-1,0,-2), range(0,max/2,2), range(1,max,2), range(max-2,0,-2)), ())