0

When you're iterating through a string with a for each loop, is it better to convert the string to a list and then loop through it? The reason I'm asking is because strings are immutable, so I'm not sure if it becomes inefficient in some way?

So, is

a = list("hello")
for i in a:
    pass

better than

a = "hello"
for i in a:
    pass

Thanks for the help.

2
  • 6
    Strings are iterable. You gain nothing by adding an extra operation (converting to a list). Commented Jan 28, 2020 at 22:31
  • 2
    If you want to "change" the string, either create a new one while looping, or convert to a list and join in the end Commented Jan 28, 2020 at 22:37

2 Answers 2

3

As has been noted, the idiomatic way is to simply iterate through the string. In fact the statement

a = list("hello")

needs to iterate through the string in order to create the list.

That said, if you are to be iterating through the same string, many times, then (after paying the cost of converting to a list) iteration through a list is faster

# string
$ python -m timeit -s "x='a'*10000" "for i in x: i"
10000 loops, best of 3: 137 usec per loop

# raw list
python -m timeit -s "x=list('a'*10000)" "for i in x: i"
10000 loops, best of 3: 113 usec per loop
Sign up to request clarification or add additional context in comments.

Comments

2

It's more idiomatic to simply iterate over the string without converting it into a list:

word = "hello"
for letter in word:
    print(letter)

2 Comments

I believe the question is how is one approach better than the other.
The question is what's the best practice. This is the most pythonic solution, given the problem description. I can't think of any reason to call list(word) for the stated use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.