Omar Gonzales
Omar Gonzales

Reputation: 4008

how to make a tuple from array

I've a list of values in an array:

 departamentos = ["Piura", "Lima"]

And I would like to transform it to:

 departamentos = (("Piura", "Piura"), ("Lima", "Lima"),)

I've tried this:

for i in departamentos:
     mis_departamentos_b  = mis_departamentos + ((i, i))

But it only returns the last item as a tuple.

mis_departamentos_b
('Lima', 'Lima')

Upvotes: 2

Views: 108

Answers (4)

hygull
hygull

Reputation: 8740

There is another way to do get the same as follows.

>>> departamentos = ["Piura", "Lima"]
>>> t = tuple(((name, ) * 2 for name in departamentos))
>>> t
(('Piura', 'Piura'), ('Lima', 'Lima'))
>>>

Detailed:

>>> departamentos = ["Piura", "Lima"]
>>>
>>> t = ((name, ) * 2 for name in departamentos)
>>> t
<generator object <genexpr> at 0x000001D13A5F8518>
>>>
>>> tuple(t)
(('Piura', 'Piura'), ('Lima', 'Lima'))
>>>

Upvotes: 0

JoshuaCS
JoshuaCS

Reputation: 2624

Besides @Claus's answer, you could also use map:

 tuple(map(lambda d: (d, d), departamentos))

(('Piura', 'Piura'), ('Lima', 'Lima'))

Upvotes: 0

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5634

Issue is in your variables. Below is modified code. You are using mis_departamentos_b and you are only assigning to it, so previous value of Plura Plura is overwritten by next value of Lima Lima

departamentos = ["Piura", "Lima"]
mis_departamentos = ()
for i in departamentos:
     mis_departamentos  = mis_departamentos + ((i, i))
print(mis_departame

Upvotes: -1

Claus Herther
Claus Herther

Reputation: 356

How about

tuple((x,x) for x in departamentos)

(('Piura', 'Piura'), ('Lima', 'Lima'))

Upvotes: 11

Related Questions