Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put a tuple into an array in python?

Tags:

I am wondering how to put a tuple into an array? or is it better to use arrays in array for the design of the program rather than a tuple in an array? please advice me. thank you

like image 772
iCezz Avatar asked Aug 14 '11 15:08

iCezz


People also ask

Is it possible to create an array from a tuple?

Yes, Any sequence that has an array-like structure can be passed to the np. array function.

Can you put tuples in a numpy array?

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.


2 Answers

One thing to keep in mind is that a tuple is immutable. This means that once it's created, you can't modify it in-place. A list, on the other hand, is mutable -- meaning you can add elements, remove elements, and change elements in-place. A list has extra overhead, so only use a list if you need to modify the values.

You can create a list of tuples:

>>> list_of_tuples = [(1,2),(3,4)] >>> list_of_tuples [(1, 2), (3, 4)] 

or a list of lists:

>>> list_of_lists = [[1, 2], [3, 4]] >>> list_of_lists [[1, 2], [3, 4]] 

The difference is that you can modify the elements in the list of lists:

>>> list_of_lists[0][0] = 7 >>> list_of_lists [[7, 2], [3, 4]] 

but not with the list of tuples:

>>> list_of_tuples[0][0] = 7 Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 

To iterate over a list of tuples:

>>> for (x,y) in list_of_tuples: ...    print x,y ...  1 2 3 4 
like image 153
jterrace Avatar answered Nov 03 '22 02:11

jterrace


if you are talking about list, you can put anything into it, even different types:

l=[10,(10,11,12),20,"test"]  l[0] = (1,2,3) l.append((4,5)) l.extend((21,22)) #this one adds each element from the tuple 

if you mean array, no python arrays don't support tuples.

like image 32
Karoly Horvath Avatar answered Nov 03 '22 01:11

Karoly Horvath