Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

reverse - Reversing a list slice in python

I am trying to reverse slice of a list in python but it returns an empty list. But when I try with whole list, it works fine. Am I missing anything here?

l=[1,2,3,4,5,6,7,8]
l[::-1]=[8, 7, 6, 5, 4, 3, 2, 1]     <<< This worked fine.

l[2:5]=[3, 4, 5]
l[2:5:-1]=[]       <<< Expecting [5,4,3] here.

Any clues?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The syntax is always [start:end:step] so if you go backwards your start needs to be greater than the end. Also remember that it includes start and excludes end, so you need to subtract 1 after you swap start and end.

l[5:2:-1]= [6, 5, 4]
l[4:1:-1]= [5, 4, 3]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...