Am I safe mixing types in a Python list?

Solution 1:

No problem, you can store any type inside a list unlike in the "olden days" when other languages had arrays that only wanted one type of data stored in them.

Since lists can also store other list, and other compound data structures, along with other object references, processing or iterating through the list may become a bit more complex due to possible multiple layers, than just going through an array in a simple single level iteration. This is also related to shallow and deep copying.

If the code processing the lists is aware of this, I can't think of any problems due to this ability to store different things in a list.

Solution 2:

The language is fine with you mixing types in a list, but you should know that the Python culture might frown on it. Tuples are usually used when you have a known collection of mixed types, and different indexes have different semantics. Lists are usually used where you have a uniform sequence of varying length.

So your data would more conventionally be represented as:

data = [
    ("name1", "long name1", 1, 2, 3),
    ("name2", "long name2", 5, 6, 7),
    ...
]

To put it more succinctly: tuples are used like C structs, lists like C arrays.

Solution 3:

There are no inherent problems in having multiple data types in a list. Problems may, of course, arise if you try to use that list for something that expects it to be all the same type. In your example, if this is all you're doing with it, there's no way for it to become a problem. You might consider, though, using a tuple instead of a list. By convention, tuples are used when the composition of the sequence is fixed; lists are used when you might add to or remove from the sequence.

Solution 4:

If you are simply using this to store different possible outputs -- which are following your function's contract of name, long_name, int1, int2, int3 -- then no problem.

If this is being used by other code that does not know the types within the list and their order, then I do see a problem. A simple example:

>>> min(['-2', 1])
1