0

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']
1

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

4 Comments

What do you mean by "if you need (mutable) lists you need to cast"? There are no casts in Python.
wouldn't you call int('123') a cast? (here i mean: list(name).)
No, that's not a cast. You're just constructing a new instance, or, more pedantically, just calling a callable that happens to construct a new instance. When you call int('123') you are simply calling int.__init__(..., '123'), and the int class can do whatever it wants with that. It can have the side effect of producing a new object with a new type that is otherwise equivalent, but that's not its primary purpose.
hmmm. i agree... i'd just have called that a cast (maybe because there is no such thing in python and this is the closest to it). but maybe i really shouldn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.