tags:

views:

127

answers:

2

So, I'm trying to append to one list the reverse of a subset of another list. For some reason, the interpreter doesn't seem to be liking it. Here's what I'm doing.

list1.extend(list2[someInt:someOtherInt].reverse())

Why is this not legit? It seems reasonable to me..

+2  A: 

list methods operate in-place, which means that they return None.

Ignacio Vazquez-Abrams
+3  A: 

In addition to Ignacio's answer, here's a solution. Try:

list1.extend(reversed(list2[someInt:someOtherInt]))

Alternatively, you can use a slice with reversed indexes, but be careful with off-by-one errors!

list1.extend(list2[someOtherInt - 1: someInt - 1: -1])

It's probably better to stick to the first method, especially as the second method will fail with 0 indexes.

Related to reversed, another trick is instead of list1.sort() you can use sorted(list1).

Mark Byers
The only problem with this answer is that it doesn't explain the actual problem, and why the question's code works the way it does.
Devin Jeanpierre
Yes, and the other answer doesn't offer a solution.
Justin Peel
@Justin: But taken together, the pair of answers completely answers the question. The purpose of the site is to answer to OPs question. Together, Ignacio and I have provided an answer. What exactly is the problem? Once the poster has accepted the answer that was most helpful for him, the accepted answer can be edited to include information from other useful posts.
Mark Byers
My comment was in response to Devin's comment. I was trying to diss the solutions.
Justin Peel