Reversing a List in Python



  • Simple list reversal using a for loop and the pop and append functions. This empties the original list as it goes. So you end up with only a single list at the end.

    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']
    newMonths = []
    
    monthlen = len(months)
    for i in range(0,monthlen):
        month = months.pop()
        newMonths.append(month)
    
    
    print(newMonths)


  • And here is a similar one but this time, both lists remain...

    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']
    newMonths = []
    
    monthlen = len(months)
    for i in range((monthlen - 1),-1,-1):
        month = months[i]
        newMonths.append(month)
    
    print(newMonths)

Log in to reply