-1

What is the pythonic way of appending returned variables (More than of one) from a function to different lists?

Suppose we got a function like:

def func():
    return np.random.randint(0, 10), np.random.randint(10, 20)

The simplest non pythonic way to do it is:

l1 = []
l2 = []

for i in range(x):
    # do something
    # do something else
    a, b = func()
    l1.append(a)
    l2.append(b)

Or using numpy:

lst = []
for i in range(x):
    # do something
    # do something else
    lst.append(func())

l1, l2 = np.array(lst).T

Or extracting items using solutions provided here.

Ravexina
  • 2,406
  • 2
  • 25
  • 41
  • Why isn't it 'Pythonic' to use your first solution ? But anyway, using numpy is in most cases, better. Without the need of the Transpose method, you could use the numpy getter [:, 0] or [:, 1] to get an entire ""column"". – IMCoins Mar 26 '19 at 09:21
  • 1
    In some situations "Pythonicness" (read: *code golf*) should be sacrificed in favor of readability, maintainability and functionality. – meowgoesthedog Mar 26 '19 at 09:22
  • `test()` should have been `func()` – DirtyBit Mar 26 '19 at 09:28
  • @Ravexina, see if the answer posted below helps? – DirtyBit Mar 27 '19 at 05:22
  • @DirtyBit Your answer is nice, however it is really similar to one which exists in the link I have mentioned in my question. Thank you ;) – Ravexina Mar 29 '19 at 08:47

2 Answers2

1

Depending on the situation, this could be much cleaner:

def func(l1, l2):
    l1.append(np.random.randint(0, 10)); l2.append(np.random.randint(10, 20))
    return l1,l2
Alec
  • 8,529
  • 8
  • 37
  • 63
1

One way could be to create a master-list and then transpose:

def func():
    return np.random.randint(0, 10), np.random.randint(10, 20)

masterLst = []    
for i in range(5):
    masterLst.append(func())

l1,l2 = zip(*masterLst)

print(list(l1))
print(list(l2))

OUTPUT:

[6, 5, 8, 6, 2]
[19, 11, 19, 10, 17]

EDIT:

Coming in from @hpaulj, a variation to the current approach:

def func():
    return np.random.randint(0, 10), np.random.randint(10, 20)

l1,l2 = list(zip(*[func() for _ in range(4)]))

print(list(l1))
print(list(l2))
DirtyBit
  • 16,613
  • 4
  • 34
  • 55