Are there unforeseen problems in mixing different types in a Python list? For example:
import random data = [["name1", "long name1", 1, 2, 3], ["name2", "long name2", 5, 6, 7]] name, long_name, int1, int2, int3 = random.choice(data)
I'm using this code to randomly set several related parameters within a function, but even though Python supports it, I'm wary of mixing types like this in a list. Since the list of mixed data types won't be used for any processing besides variable assignment in and of itself (the variables it assigns to will, but not the list itself), I presume this is fine, but I want to make sure this isn't secretly problematic code.
Like we said, you can store a number, a string, and even another list within a single list. It's okay to mix data types!
Items in a list do not have to all be the same type, either. They can be any Python object. (Here, assume Three is a function.) Note that having mixed objects in a list can have implications for sorting the list.
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.
Answer. A list in Python CAN contain different types of data. Each item in the list is separated by a comma and the entire list is enclosed in square brackets [] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With