'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
Solution 1:[1]
Use slicing on any sequence to reverse it :
print(list[::-1])
Solution 2:[2]
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]
Solution 3:[3]
Do you want to reverse your list?
a = ['car1', 'car2', 'car3']
a.reverse()
print(a)
['car3', 'car2', 'car1']
Solution 4:[4]
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!
Solution 5:[5]
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)
Solution 6:[6]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user426 |
| Solution 2 | Darkknight |
| Solution 3 | Corralien |
| Solution 4 | Muhammad Rizwan |
| Solution 5 | |
| Solution 6 | yogender |
