gliese581g
gliese581g

Reputation: 443

Does tuple sort itself when looped through

I have a tuple which contains multiple values which I use for searching in some file. I get this tuple as an input parameter to my method. I try to search for that value(text) in one file and returns related result. But I have a requirement that if that text is not found then search for the value 'Unknown' in that file and return corresponding value. To achieve this I am planning to append value 'Unknown' to the tuple so that if it doesn't find anything, it will return something corresponding to 'Unknown'. But my question is that if I apeend 'Unknown' at last, while looping through this tuple does it loop through in the same order which the elements were added to it? I have tried it on python shell and noticed that it loops through it in the same order. But I don't want my code to accidentally search for 'Unknown' value before desired ones. Please help.

Upvotes: 0

Views: 50

Answers (2)

salezica
salezica

Reputation: 76919

When you say tuple, I think you mean list. Tuples don't have an append operation, they are fixed in size.

If you append to a list while iterating, you'll get the expected result. It's not good practice, however, to alter a collection while walking it.

A much better approach is to collect items to be appended in a second list, and concatenate the two lists when you finish iterating the first.

Upvotes: 1

user2357112
user2357112

Reputation: 280485

Looping over a tuple always goes from the first element to the last.

>>> for x in ('asdf', 5, None):
...     print x
...
asdf
5
None

Upvotes: 1

Related Questions