Dan
Dan

Reputation: 43

Is ordered ensured in list iteration in Python?

Let's suppose to have a list of strings, named strings, in Python and to execute this line:

lengths = [ len(value) for value in strings ]

Is the strings list order kept? I mean, can I be sure that lengths[i] corresponds to strings[i]? I've tryed many times and it works but I'm not sure if my experiments were special cases or the rule.

Thanks in advance

Upvotes: 1

Views: 56

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45742

For lists, yes. That is one of the fundamental properties of lists: that they're ordered.

It should be noted though that what you're doing though is known as "parallel arrays" (having several "arrays" to maintain a linked state), and is often considered to be poor practice. If you change one list, you must change the other in the same way, or they'll be out of sync, and then you have real problems.

A dictionary would likely be the better option here:

lengths_dict = {value:len(value) for value in strings}
print(lengths_dict["some_word"])  # Prints its length

Or maybe if you want lookups by index, a list of tuples:

lengths = [(value, len(value)) for value in strings]
word, length = lengths[1]

Upvotes: 1

Leo Arad
Leo Arad

Reputation: 4472

Yes, since list in python are sequences you can be sure that each length that you have in the list of the length is corresponding to the string length in the same index. like the following code represents

a = ['a', 'ab', 'abc', 'abcd'] 
print([len(i) for i in a])

Output

[1, 2, 3, 4]

Upvotes: 0

Related Questions