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

3
  • 2
    It does, and it is. If this is a concern, I think itertools.islice might be of use Commented Jun 28, 2016 at 7:55
  • 1
    Oh yeah, it's the exact same question. I guess I didn't know how to properly word it. Commented Jun 28, 2016 at 8: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. Commented Jun 28, 2016 at 8:07

1 Answer 1

1

Yes it does.

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

This works the same with lists too.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.