0

I have three lists in python. Let's say :

list_a
list_b
list_c

Now I am calling a method which also return a list and save into the above lists. For example:

list_a = get_value(1)
list_b = get_value(2)
list_c = get_value(3)

I think the way I choose to call a same methods with different parameters are not a good option. Would it be possible for us to call these methods within one line?

I am beginner in Python, but what about the tuple option?

1
  • 2
    Note that the line list_a = get_value(1) does not "save the return value into the above list". You would need to use list_a[:] = get_value(1) instead. Commented Jul 13, 2012 at 12:01

3 Answers 3

3

A list of lists?

ll = [get_value(x) for x in (1, 2, 3)]

or with your three lists:

list_a, list_b, list_c = [get_value(x) for x in (1, 2, 3)]

taking into account, that get_value cannot be modified and returns just the single list.

Another possibility would be a dictionary.

params = {'a': 1, 'b': 2, 'c': 3}
result = {k:get_value(v) for k,v in params.iteritems()}
# result == {'a': get_value(1), 'b': get_value(2), 'c': get_value(3)}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 nice (and I was just going to suggest the unpacking to the 3 variables)
you could even use a generator for this, not sure if it would actually be more efficient for large sets of data.
3

If your function was set up correctly (ie modified to return the same number of lists as you send in parameters) you could have a call that looked like this:

 list_a, list_b, list_c = get_value(1, 2, 3)

where get_value() would return a tuple of 3 values.

Is that what you are asking about?

Comments

2

Another way:

list_a, list_b, list_c = map(get_value, (1,2,3))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.