Is the execution order guaranteed when looping through the string?

Is the program below guaranteed to always produce the same output?

s = 'fgvhlsdagfcisdghfjkfdshfsal'
for c in s:
    print(c)

      

+3


source to share


5 answers


Yes it is. This is because the type str

is an immutable sequence. Sequences are a finite ordered set of elements (see Sequences in the Data Model chapter of the Reference Manual).



Iterating through a given string (any sequence) is guaranteed to always give the same results in the same order for different runs of the CPython interpreter, CPython versions, and Python implementations.

+5


source


Yes. The inner string you store there is stored in a c-style array (depending on the interpreter implementation), being a sequential array of data, an iterator can be created . To use the syntax for ... in ...

, you must be able to iterate over the object after the line. The string provides its own iterator that allows you to parse it with the syntax in the following order: execute all python sequences .



The same is true for lists and even custom objects that you create. However, not all repeating python objects will necessarily be in order or represent the values ​​they store, a dictionary is a clear example of this . The dictionary iterator gives keys that may or may not be in the order you added them (depending on the version of python you are using among other things, so don't assume it is ordered if you don't use OrderedDict) instead of sequential values ​​like as list tuple and string.

+3


source


Yes it is. Along the line, the for-loop iterates through the characters in order. This is also true for lists and tuples - the for loop will iterate over the elements in order.

You can think of sets and dictionaries. They don't indicate a specific order, so:

for x in {"a","b","c"}:  # over a set
    print(x)

for key in {"x":1, "y":2, "z":3}:  # over a dict
    print(key)

      

will iterate at random, which you can't easily predict in advance.

See this stack overflow answer for more information on what guarantees are made for the order of dictionaries and sets.

+3


source


Yes. The for loop is sequential.

+2


source


Yes, the loop will always print each letter one by one, starting with the first character and ending with the last.

+1


source







All Articles