1

Let's say I have a str of length 5: Hello. If I wanted to iterate through every character from index 1 on, I'd do it like this:

s = 'Hello'
for c in s[1:]:
    # do something

Does looping like this create a new str object of length 4? I can see it being very memory inefficient with bigger strings...

shooqie
  • 950
  • 7
  • 17
  • 2
    It does, and it is. If this is a concern, I think [`itertools.islice`](https://docs.python.org/2.7/library/itertools.html#itertools.islice) might be of use – jonrsharpe Jun 28 '16 at 07:55
  • 1
    Oh yeah, it's the exact same question. I guess I didn't know how to properly word it. – shooqie Jun 28 '16 at 08:05
  • 1
    @shooqie No worries, appreciated for marking it as a duplicate yourself and having a thoughtful question. Just an FYI, Google can often be a better resource than the Stack Overflow search bar for finding questions on Stack Overflow, as strange as that may sound. – miradulo Jun 28 '16 at 08:07

1 Answers1

1

Yes it does.

Also, doing s[:] will create a new string identical to the previous.

This works the same with lists too.

Amit Gold
  • 727
  • 7
  • 22