Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSamoro Palacios
2,430 PointsConfused on negative step
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[3:6:-1]
print(colors_partial)
When I entered this the output was an empty list. From what I understand a negative step is just supposed to count from the end of the list as opposed to the beginning. So why wouldn't this work?
1 Answer
Joseph Yhu
PHP Development Techdegree Graduate 48,638 Pointscolors_partial = colors[3:6:-1]
You are telling the program to go from index 3 to the end backwards. The correct way is:
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[6:3:-1]
print(colors_partial)
Since index 6 is the end you can also do:
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[-1:3:-1]
print(colors_partial)
You can leave out the first part entirely too:
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[:3:-1]
print(colors_partial)
All three will print ['violet', 'indigo', 'blue']
.
Samoro Palacios
2,430 PointsSamoro Palacios
2,430 PointsSo I think I understand the issue now. Please correct me if I'm wrong. The negative step doesn't change the index number of the list. So when I told it to count backwards from the index 3. Index 6 was no longer in that range so it output was empty? Thank you!