Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Convaly Avatar asked Apr 25 '26 17:04

Convaly


1 Answers

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]
like image 179
chepner Avatar answered Apr 27 '26 05:04

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!