Reputation: 31
My task is to create an empty array and take the input from the user, but I have to print the input element in a reversed order without the function, that too in an array itself.
x=int(input('how many cars do you have'))
a=[]
for i in range(x):
car=(input('enter your car name'))
a.append(car)
print(a)
y=[]
for i in range(length(a)-1,-1,-1):
y.append(a[i])
print (y)
Why am i getting repeated reverse array output with this code. Can anyone please tell me what's wrong in this
Upvotes: 3
Views: 2265
Reputation: 586
Simple Custom way (without using built-in functions) to reverse a list:
def rev_list(mylist):
max_index = len(mylist) - 1
return [ mylist[max_index - index] for index in range(len(mylist)) ]
rev_list([1,2,3,4,5])
#Outputs: [5,4,3,2,1]
Upvotes: 0
Reputation: 1836
If your looking for a method from scratch without using any built-in function this one would do
arr = [1,2,3,5,6,8]
for i in range(len(arr)-1):
arr.append(arr[-2-i])
del(arr[-3-i])
print(arr)
# [8, 6, 5, 3, 2, 1]
Upvotes: 1
Reputation: 160
Your code is giving me the correct output except that
len()
is used to calculate the length of a list and not length()
.
x=int(input('how many cars do you have'))
a=[]
for i in range(x):
car=(input('enter your car name'))
a.append(car)
print(a)
y=[]
for i in range(len(a)-1,-1,-1):
y.append(a[i])
print(y)
Upvotes: 0
Reputation: 177
you should use slicing. for example,
a = ['1','2','3']
print(a[::-1])
will print ['3','2','1']
. I hope this will work for you.
Happy Learning!
Upvotes: 0