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 trialfahad lashari
7,693 PointsCan anybody demonstrate a for loop with a slice? like mentioned at the end of the video
Can anybody demonstrate a for loop with a slice? like mentioned at the end of the video.
Would greatly appreciate it as I do not really understand what Kenneth meant by it.
kind regards,
Fahad
2 Answers
andren
28,558 PointsHe simply meant that slices can be used as a source for a loop just like a string or list. So if I wanted to print the 6 last characters of a string for example I could use a loop like this:
example = "Hello World!"
for letter in example[-6:]:
print(letter)
Now that is not a very useful loop but it would work, and that is what Kenneth meant, if slices were not considered iterable then they could not have been used as a source for a loop at all.
And his negative step example looks something like this:
example = "Hello World!"
for letter in example[::-1]:
print(letter)
That would print the string in reverse since it would be stepped through starting from the end and moving backwards. Both of these examples would of course also work if a list were sliced instead of a string.