Q:

Print list in reverse order using a loop using python programming

belongs to collection: Python Loop Exercises

0

Print list in reverse order using a loop

Given:

list1 = [10, 20, 30, 40, 50]

Expected output:

50
40
30
20
10

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

Approach 1: Use the built-in function reversed() to reverse the list

Approach 2: Use for loop and the len() function

  • Get the size of a list using the len(list1) function
  • Use for loop and reverse range() to iterate index number in reverse order starting from length-1 to 0. In each iteration, i will be reduced by 1
  • In each iteration, print list item using list1[i]. i is the current value if the index

Solution1:Using a reversed() function and for loop

list1 = [10, 20, 30, 40, 50]
# reverse list
new_list = reversed(list1)
# iterate reversed list
for item in new_list:
    print(item)

Solution2:Using for loop and the len() function

list1 = [10, 20, 30, 40, 50]
# get list size
# len(list1) -1: because index start with 0
# iterate list in reverse order
# star from last item to first
size = len(list1) - 1
for i in range(size, -1, -1):
    print(list1[i])

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Display numbers from -10 to -1 using for loop usin... >>
<< Write a python program to use for loop to print th...