Deqing
Deqing

Reputation: 14632

How to get part of a list in return values

I'd like to return several values in a method, including a list.

Following works fine:

def foo():
  a = 42
  b = [1,2]
  return a, b

aa, b_list = foo()      
aa, (b1, b2) = foo()

But I don't know how get a list without first element:

def bar():
  a = 42
  b = [1,2,3]
  return a, b

aa, (_, b_list) = bar()
print(b_list)  # Expecting [2,3]
# ValueError: too many values to unpack (expected 2)

Yes I can get the list and drop first element, but is there a one-liner for this?

This function is supposed be versatile, for example should be supporting two scenarios:

aa, whole_list = foo()
aa, first_elem, rest_of_the_list = foo()

Upvotes: 1

Views: 723

Answers (4)

Prune
Prune

Reputation: 77827

This is called a list slice; you can return a contiguous range of the list, such as

return a, b[1:]

This notation gives you elements 1 through the end -- everything but the first element.

If you need to drop the first item after the return, just use the same syntax:

print(b_list[1:])

or permanently alter (until the next assignment) b_list with

b_list = b_list[1:]

Upvotes: 1

theodox
theodox

Reputation: 12208

Not exactly a one liner, but I'd try using a namedtuple to make the nature of the retval clearer

from collections import namedtuple
retval = namedtuple('retval', 'scalar list')

def bar():
  a = 42
  b = [1,2,3]
  return retval(a, b)

rv = bar()
a, b = rv.scalar, rv.list[1:]

Upvotes: 1

Uriel
Uriel

Reputation: 16174

Yes, there is. You can use unpacking for b_list:

aa, (_, *b_list) = bar()
  • Note this works only in python 3.

Upvotes: 5

question
question

Reputation: 19

so from what i understand you want to get a back which is 42 and be back which is 1,2,3

i would try

def bar():
  a = 42
  b = [1,2,3]
  return a, b

a, b = bar()
print(b)  # Expecting [2,3]
print(aa)

Upvotes: -1

Related Questions