Reputation:
I have a function that creates two lists. I want the function to return the two lists as [], []
.
Here is the code. This returns a list that look like this [[], []]
, close but still not what I want.
def create_xy_lst(start, length, step, up, down):
new_list = []
new_list.append(create_x_lst(start, length, step))
new_list.append(create_y_lst(start, length, up, down))
return new_list
Then I tried a different approach. This returns ([], [])
which is a tuple.
def create_xy_lst(start, length, step, up, down):
x = (create_x_lst(start, length, step))
y = (create_y_lst(start, length, up, down))
return x, y
How can I make the function return [], []
?
Python 2.7
Upvotes: 2
Views: 2785
Reputation: 82470
[], []
is a tuple. ()
is simple there for syntax, let me demonstrate:
>>> hello = 1,
>>> hello
(1,)
>>> cheese = [1,2,3], [6,7,8]
>>> cheese
([1, 2, 3], [6, 7, 8])
As you can see the ,
is what makes a tuple.
And you can unpack them like so:
>>> a, b = [1,2], [3,4]
>>> a
>>> [1,2]
>>> b
>>> [3,4]
So, in your function:
x, y = create_xy_lst(start, length, step, up, down)
This is also a neat trick (if you're in Python 3) if you have more than one list in the tuple:
>>> a, *b = [2], [4,5,6], [10]
>>> a
>>> [2]
>>> b
>>> ([4,5,6], [10])
If however, you simple want to return one list
, you can do this:
return x + y
Upvotes: 3
Reputation: 7806
You are asking about a tuple but you are rejecting the idea that it should be a tuple so here is another idea. You could turn it into a generator.
def create_xy_lst(start, length, step, up, down):
yield create_x_lst(start, length, step))
yield create_y_lst(start, length, up, down))
which will only yield 1 list per query.
val = create_xy_lst(a,b,c,d,e)
print(val.next()) #first list
print(val.next()) #second list
or you could loop over it
for val in create_xy_lst(a,b,c,d,e):
print(val)
Upvotes: 0
Reputation: 239463
def returnNumbers():
return 1, 2
first, second = returnNumbers()
print first, second
It will print
1 2
You can simply return a tuple and unpack the values like shown in the example.
You can even check the type of data returned by the function like this
print type(returnNumbers())
it will print
<type 'tuple'>
Upvotes: 1
Reputation: 1085
Your second try is (mostly) the right way (you just don't need the parenthesis around your function calls).
I'm guessing you're retrieving your results like this:
foo = create_xy_list(...)
try this instead:
foo, bar = create_xy_list(...)
Upvotes: 0
Reputation: 1121714
[], []
is a tuple:
>>> [], []
([], [])
The comma makes the value a tuple, not the parenthesis.
Returning x, y
is the correct way to return multiple values.
You can unpack tuples into multiple variables:
x, y = [], []
and this works just fine for function return values too:
x, y = create_xy_lst(...)
Unpacking in an assignment is not limited to just tuples; it works with any sequence:
char1, char2, char3 = 'foo'
Upvotes: 7