How can I reverse a list in Python?

后端 未结 30 2610
既然无缘
既然无缘 2020-11-21 22:32

How can I do the following in Python?

array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of a

相关标签:
30条回答
  • 2020-11-21 23:10

    You can make use of the reversed function for this as:

    >>> array=[0,10,20,40]
    >>> for i in reversed(array):
    ...     print(i)
    

    Note that reversed(...) does not return a list. You can get a reversed list using list(reversed(array)).

    0 讨论(0)
  • 2020-11-21 23:10

    Using some logic

    Using some old school logic to practice for interviews.

    Swapping numbers front to back. Using two pointers index[0] and index[last]

    def reverse(array):
        n = array
        first = 0
        last = len(array) - 1
        while first < last:
          holder = n[first]
          n[first] = n[last]
          n[last] = holder
          first += 1
          last -= 1
        return n
    
    input -> [-1 ,1, 2, 3, 4, 5, 6]
    output -> [6, 1, 2, 3, 4, 5, -1]
    
    0 讨论(0)
  • 2020-11-21 23:10

    Can be done using __reverse__ , which returns a generator.

    >>> l = [1,2,3,4,5]
    >>> for i in l.__reversed__():
    ...   print i
    ... 
    5
    4
    3
    2
    1
    >>>
    
    0 讨论(0)
  • 2020-11-21 23:11

    use

    print(reversed(list_name))
    
    0 讨论(0)
  • 2020-11-21 23:12
    >>> L = [0,10,20,40]
    >>> L[::-1]
    [40, 20, 10, 0]
    

    Extended slice syntax is explained well in the Python What's new Entry for release 2.3.5

    By special request in a comment this is the most current slice documentation.

    0 讨论(0)
  • 2020-11-21 23:13

    Reverse of a user input values in one line code:

    for i in input()[::-1]: print(i,end='')
    
    0 讨论(0)
提交回复
热议问题