Is it possible to return two lists from a function in python
You can return a tuple of lists, an use sequence unpacking to assign them to two different names when calling the function: def f(): return [1, 2, 3], [“a”, “b”, “c”] list1, list2 = f()
You can return a tuple of lists, an use sequence unpacking to assign them to two different names when calling the function: def f(): return [1, 2, 3], [“a”, “b”, “c”] list1, list2 = f()
A single star * unpacks a sequence or collection into positional arguments. Suppose we have def add(a, b): return a + b values = (1, 2) Using the * unpacking operator, we can write s = add(*values), which will be equivalent to writing s = add(1, 2). The double star ** does the same thing … Read more
for i, (letter, word) in enumerate(seq_nested): print i, letter, word
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples. >>> T=(1,) >>> a=T >>> a (1,) >>> b,=T >>> b 1 >>> a is tuple, b is an integer.
You can’t use * iterable unpacking in a list comprehension, that syntax is only available in calls, and in Python 3, when using assignments. If you want to use a list comprehension, just put your for loops in series; you do want to access the values from my_list directly rather than generate indices though: [v … Read more
The error occurs because (a) is just a value surrounded by parenthesis. It’s not a new tuple object. Thus, ‘%d %d’ % (*a) is equivalent to ‘%d %d’ % * a, which is obviously wrong in terms of python syntax. To create a new tuple, with one expression as an initializer, use a comma after … Read more
I found out that the related PEP3132 gives some examples for Python 2.x as well: Many algorithms require splitting a sequence in a “first, rest” pair: first, rest = seq[0], seq[1:] […] Also, if the right-hand value is not a list, but an iterable, it has to be converted to a list before being able … Read more
Add another level, with a tuple (just the comma): (k, v), = d.items() or with a list: [(k, v)] = d.items() or pick out the first element: k, v = d.items()[0] The first two have the added advantage that they throw an exception if your dictionary has more than one key, and both work on … Read more
In Python, every iterable can be unpacked1: >>> x,y,z = [1, 2, 3] # A list >>> x,y,z (1, 2, 3) >>> x,y,z = 1, 2, 3 # A tuple >>> x,y,z (1, 2, 3) >>> x,y,z = {1:’a’, 2:’b’, 3:’c’} # A dictionary >>> x,y,z (1, 2, 3) >>> x,y,z = (a for a … Read more