Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Slices Deleting Or Replacing Slices

fahad lashari
fahad lashari
6,771 Points

Can 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
andren
28,550 Points

He 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.