fathima abdulla
fathima abdulla

Reputation: 31

python code to reverse an array without using the function

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

Answers (5)

yogender
yogender

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

Darkknight
Darkknight

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

HiEd
HiEd

Reputation: 160

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)

Upvotes: 0

Muhammad Rizwan
Muhammad Rizwan

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

user426
user426

Reputation: 293

Use slicing on any sequence to reverse it :

print(list[::-1])

Upvotes: 1

Related Questions