Convaly
Convaly

Reputation: 49

Unpack into the list append method in Python

I run into a problem when unpacking a tuple. I want the first value to be appended to a list and a second assigned to a variable. For example:

list = []
tuple = (1, 2)

list.append, variable = tuple

But this raises an exception since I am assigning to a bultin and not actually calling in. Is that possible in Python? Or even a simpler operation such as:

a, b = 5, 4
tuple = (1, 2)

a+, b = tuple

to yield a = 6, b = 2.

Upvotes: 3

Views: 6706

Answers (4)

abel gladstone
abel gladstone

Reputation: 11

You can use the map function on the append method for the list.

>>> a = (6,7)
>>> b = [1,2,3,4,5]
>>> list(map(b.append, a))
[None, None]
>>> b
[1, 2, 3, 4, 5, 6, 7]

I am not really sure what the list() does in this statement but it seems to work.

Upvotes: 1

chepner
chepner

Reputation: 532508

There's no brief syntax to allow this. However, here's a class that creates a wrapper around a list, so that assigning to an append attribute really calls the underlying list's append method. This could be useful if you have a lot of values to append to the list.

class Appender:
    def __init__(self, lst):
        self.lst = lst

    # The rare write-only property
    append = property(None, lambda self, v: self.lst.append(v))


values = []
value_appender = Appender(values)

value_appender.append, b = (1,2)
assert values == [1]

Perhaps simpler, a subclass of list with a similar property:

class Appendable(list):
    take = property(None, lambda self, v: self.append(v))

values = Appendable()
values.take, b = (1, 2)
assert values == [1]

Upvotes: 4

Chris
Chris

Reputation: 16182

Technically yes you could do it in a single line, but I wouldn't.

l = []
a = (1,2)
l[:0], b = [[x] if c == 0 else x for c,x in enumerate(a)]
>>> l
[1]
>>> b
2

Upvotes: 0

ekneiling
ekneiling

Reputation: 157

append is a method on the builtin list type. Python allows tuple unpacking into variables in one line as a convenience, but it won't decide to call the append method with part of your tuple as an argument. Just write your code on multiple lines, that will help make it easier to read too.

my_list = []
my_tuple = (1, 2)
a, b = my_tuple
my_list.append(a)

Upvotes: 2

Related Questions