Reversing a list using slice notation

后端 未结 8 1858
忘掉有多难
忘掉有多难 2020-11-28 22:49

in the following example:

foo = [\'red\', \'white\', \'blue\', 1, 2, 3]

where: foo[0:6:1] will print all elements in foo. Howe

相关标签:
8条回答
  • 2020-11-28 23:24

    This answer might be a little outdated, but it could be helpful for someone who stuck with same problem. You can get reverse list with an arbitrary end - up to 0 index, applying second in-place slice like this:

    >>> L = list(range(10))
    >>> L
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> (start_ex, end) = (7, 0)
    >>> L[end:start_ex][::-1]
    [6, 5, 4, 3, 2, 1, 0]
    
    0 讨论(0)
  • 2020-11-28 23:27

    You can get it to work if you use a negative stop value. Try this:

    foo[-1:-7:-1]
    
    0 讨论(0)
提交回复
热议问题