Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append elements of a set to a list in Python

Tags:

python

list

set

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]
like image 809
tronman Avatar asked Jan 19 '11 22:01

tronman


People also ask

Can I append a set to a list Python?

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.

How do I add elements to a list in a set?

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.


1 Answers

Use

a.extend(list(b))

or even easier

a.extend(b)

instead.

like image 75
Sven Marnach Avatar answered Oct 18 '22 20:10

Sven Marnach