ML
    • Register
    • Login
    • Search
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups

    Reversing a List in Python

    Developer Discussion
    python 3 python
    1
    2
    1191
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • scottalanmiller
      scottalanmiller last edited by scottalanmiller

      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)
      
      1 Reply Last reply Reply Quote 0
      • scottalanmiller
        scottalanmiller last edited by

        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)
        
        1 Reply Last reply Reply Quote 0
        • First post
          Last post