How do you append the elements of a set to a list in Python in the most succinct way?
>>> a = [1,2]
>>> b = set([3,4])
>>> a.append(list(b))
>>> a
[1, 2, [3, 4]]
But what I want is:
[1, 2, 3, 4]
Whereas, sets in Python are immutable and does not allow unhashable objects. Therefore, Python does not allow a set to store a list. You cannot add a list to a set. A set is an unordered collection of distinct hashable objects.
To add a list to set in Python, use the set. update() function. The set. update() is a built-in Python function that accepts a single element or multiple iterable sequences as arguments and adds that to the set.
Use
a.extend(list(b))
or even easier
a.extend(b)
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With