Jawad Sleiman
Jawad Sleiman

Reputation: 55

Python Array Variable Assign

I have the following array in Python in the following format:

Array[('John', '123'), ('Alex','456'),('Nate', '789')]

Is there a way I can assign the array variables by field as below?

Name = ['john', 'Alex', 'Nate']
ID = ['123', '456', '789']

Upvotes: 0

Views: 623

Answers (2)

Daniel Pryden
Daniel Pryden

Reputation: 60997

In the spirit of "explicit is better than implicit":

data = [('John', '123'), ('Alex', '456'), ('Nate', '789')]

names = [x[0] for x in data]
ids = [x[1] for x in data]


print(names) # prints ['John', 'Alex', 'Nate']
print(ids)  # prints ['123', '456', '789']

Or even, to be even more explicit:

data = [('John', '123'), ('Alex', '456'), ('Nate', '789')]
NAME_INDEX = 0
ID_INDEX = 1

names = [x[NAME_INDEX] for x in data]
ids = [x[ID_INDEX] for x in data]

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46921

this is a compact way to do this using zip:

lst = [('John', '123'), ('Alex','456'),('Nate', '789')]

name, userid = list(zip(*lst))

print(name)   # ('John', 'Alex', 'Nate')
print(userid)  # ('123', '456', '789')

note that the results are stored in (immutable) tuples; if you need (mutatble) lists you need to cast.

Upvotes: 0

Related Questions