0
why this code is not printing the reverse list!
numbers = list(range(3, 8)) print(numbers) n = numbers.reverse() print(n)
5 Respostas
+ 5
took me a bit to figure it out myself! the reason is that list.reverse () does not return a value, but instead reverses the list in place. because there is no return value, the variable n is equal to None. Instead, use the following code:
numbers = list (range (3,8))
print(numbers)
numbers.reverse ()
print (numbers)
note: this changes the list entirely, so if you are accessing the list via indexes using the reverse method will screw that up.
+ 2
never heard of using .reverse()
reversing positions in a list is done like so:
reverse = list[::-1]
+ 1
Lists are mutable.
So, numbers.reverse() does not have a return .
It manipulates ths list numbers to whatever you want.
numbers = range(3,8)
print numbers
numbers.reverse()
print numbers
Unlike tuples witch are not mutable, a tuple does not have a reverse method to manipulate like in lists or range.
So if you want to reverse a tuple you should copy its items to something that is mutable like a list or a range.
tuple = (1,2,3,4,5)
list_tuple_items_reversed = []
i = len(tuple)
while i > 0:
list_tuple_items_reversed.append(tuple[i-1])
i -= 1
print list_tuple_items_reversed
0
thanks Luke.. made it clear now..
thanks vyavas.. I am still in basics and experimenting it..
0
vyavas and Luke both thanks