0

why this code is not printing the reverse list!

numbers = list(range(3, 8)) print(numbers) n = numbers.reverse() print(n)

21st Sep 2016, 4:02 PM
shiv
shiv - avatar
5 Answers
+ 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.
21st Sep 2016, 10:11 PM
Luke Armstrong
+ 2
never heard of using .reverse() reversing positions in a list is done like so: reverse = list[::-1]
21st Sep 2016, 5:22 PM
vyavas
+ 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
21st Feb 2017, 8:09 AM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
0
thanks Luke.. made it clear now.. thanks vyavas.. I am still in basics and experimenting it..
22nd Sep 2016, 3:09 PM
shiv
shiv - avatar
0
vyavas and Luke both thanks
24th Sep 2016, 12:19 PM
Ahmed Kamal
Ahmed Kamal - avatar