Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I safe mixing types in a Python list?

Tags:

python

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 image 599
Ricardo Altamirano Avatar asked Jul 09 '12 00:07

Ricardo Altamirano


People also ask

Can you mix types in a Python list?

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!

Can list have mixed data type?

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.

Can we store different data types in 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.

Can a Python list have different types of elements?

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 [] .


1 Answers

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.

like image 88
Levon Avatar answered Sep 28 '22 03:09

Levon