Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
combining lists
#1
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])
Yoriz write Feb-08-2022, 06:19 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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.
Reply
#3
Thanks a lot :-)
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,387 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  combining lists in a dictionary Skaperen 9 3,474 Nov-04-2019, 05:28 PM
Last Post: DeaD_EyE
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,293 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020