I'm a beginner in Python. I try to create a list from 1~5 then print out the reverse list and combine them like [1,2,3,4,5,5,4,3,2,1]
and here is my working.
num1 = list(range(1,6))
num2 = num1.reverse()
print(num1)
print(num2)
print(num1.extend(num2))
Output of num1 is reverse [5,4,3,2,1]
. Output of num2 is None
and the extend function not working. How .reverse()
and .extend()
really work?
list.reverse()
does the reversal in-place - so your original list is reversed. And also, the reverse()
method returns None
Hence your num1
get reversed & num2
is None
.
Similarly, extend
also modifies the argument list & returns None
To make this work:
num1 = list(range(1,6))
num2 = num1[::-1]
print(num1)
print(num2)
num1.extend(num2)
print(num1)
Gives:
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]