[Tutor] Rearranging a list

Steven D'Aprano steve at pearwood.info
Thu Feb 26 13:40:20 CET 2015


On Thu, Feb 26, 2015 at 07:13:57AM -0500, Ken G. wrote:
> Assuming I have the following list and code how do I best be able 
> rearrange the list as stated below:
> 
> list = [0, 0, 21, 35, 19, 42]

Be aware that you have "shadowed" the built-in list function, which 
could cause trouble for you.

py> list = [1, 2, 3]
py>     # much later, after you have forgotten you shadowed list...
py> characters = list("Hello world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable


Oops.

Save yourself future hassles, and pick a name like "L" (don't use "l", 
since that looks too similar to digit 1) or "mylist" or "seq" (short for 
sequence).


> Using print list[2:6] resulted in the following:
> 
> 2    21
> 3    35
> 4    19
> 5    42

I'm pretty sure it doesn't.

py> lst = [0, 0, 21, 35, 19, 42]
py> print(lst[2:6])
[21, 35, 19, 42]

You're obviously doing a lot more than just `print lst[2:6]` to get the 
output you say you are getting.

 
> I would like to rearrange the list as follow:
> 
> 5    42
> 3    35
> 2    21
> 4    19

I don't understand how to generalise that. If you know you want that 
EXACT output, you can say:

print "5    42"
print "3    35"

etc. to get it. Obviously that's not what you want, but I don't 
understand what rule you used to get "5   42" first, "3   35" second, 
etc. Where does the 5, 3, 2, 4 come from? What's the rule for getting 42 
first, 19 last?


> I tried using list.reverse() and print list[0,6] and it resulted in:
> 
> [42, 19, 35, 21, 0, 0] or as printed:
> 
> 0    42
> 1    19
> 2    35
> 3    21
> 4    0
> 5    0
> 
> In another words, I would desire to show that:
> 
> 5 appears 42 times
> 3 appears 35 times
> 2 appears 21 times
> 4 appears 19 times

Huh? Now I'm *completely* confused. Your list was:

[0, 0, 21, 35, 19, 42]

5, 3, 2 and 4 don't appear *at all*. You have:

0 appears twice
21 appears once
35 appears once
19 appears once
42 appears once


> but then I lose my original index of the numbers by reversing. How do I 
> best keep the original index number to the rearrange numbers within a list?

No clue what you mean.



-- 
Steve


More information about the Tutor mailing list