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']
khelwood
  • 55,782
  • 14
  • 81
  • 108
Jawad Sleiman
  • 55
  • 1
  • 9
  • 1
    Possible duplicate of [How to split a list of 2-tuples into two lists?](https://stackoverflow.com/questions/21867303/how-to-split-a-list-of-2-tuples-into-two-lists) – joel Mar 11 '19 at 13:54

2 Answers2

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]
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • What do you mean by "if you need (mutable) `list`s you need to cast"? There are no casts in Python. – Daniel Pryden Mar 11 '19 at 13:54
  • wouldn't you call `int('123')` a cast? (here i mean: `list(name)`.) – hiro protagonist Mar 11 '19 at 13:58
  • 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. – Daniel Pryden Mar 11 '19 at 17:49
  • 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. – hiro protagonist Mar 11 '19 at 19:09