Python Forum

Full Version: combining lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there

Can somebody explain why my statement for c also results in a list and not in a set (as the set brackets where used)?
(This is just to understand what is actually happening - I'm not interested in other ways to do it ;-)

a = [5, 5, 1, 45, 3]
b = [3, 8, 92, 5, 45, 6]

c = sorted({x for x in a if x in b})
d = sorted([x for x in a if x in b])
Because sorted takes an iterable argument and returns a list. It doesn't care about the type of the argument as long it is iterable.

From the documents: https://docs.python.org/3/library/functions.html#sorted

Quote:sorted(iterable, /, *, key=None, reverse=False)
Return a new sorted list from the items in iterable.
Thanks a lot :-)
One other thing. You can't sort a set. By definition a set is an unordered collection.

From the docs: https://docs.python.org/3/tutorial/datas....html#sets
Quote:Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
If you put sorted values in a set they will not retain their order.