3

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

1
  • HiEd's answer is correct. Your print (y) is indented, meaning it's in the if statement, meaning with every iteration it prints y. So just remove the indentation/four spaces in front of print (y). Commented Jul 28, 2021 at 9:45

5 Answers 5

1

Use slicing on any sequence to reverse it :

print(list[::-1])
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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!

Comments

0

enter image description hereYour 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)

2 Comments

how many cars do you have3 enter your car nameswift ['swift'] enter your car namebaleno ['swift', 'baleno'] enter your car namebolero ['swift', 'baleno', 'bolero'] ['bolero'] ['bolero', 'baleno'] ['bolero', 'baleno', 'swift'].... i am talking about the third last and second last line.... is it possible to get just the last line.
I have added a screenshot of the output in my answer. I just get ['bolero', 'baleno', 'swift'] as the output.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.