What is set() function used for?

0 votes

In python, set() is an unordered collection with no duplicate elements. However, I am not able to understand how it generates the output.

For example, consider the following:

>>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
>>> set(x)
set([1, 2, 3])

>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> set(y)
set([8, 1, 6])

>>> z = [1, 1, 6, 6, 6, 6, 6, 7, 7]
>>> set(z)
set([1, 6, 7])

Shouldn't the output of set(y) be: set([1, 6, 8])? I tried the above two in Python 2.6.

Oct 17, 2018 in Python by findingbugs
• 4,730 points
10 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).

If you'd like to sort them, you can simply perform:

sorted(set(y))

which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)

Otherwise, the only thing guaranteed by set is that it makes the elements unique (nothing will be there more than once).

answered Oct 17, 2018 by Priyaj
• 56,120 points

Related Questions In Python

0 votes
1 answer

.join() method is used for what purpose in Python?

join() method is used to concatenate or ...READ MORE

answered May 14 in Python by Taj
• 340 points
10 views
0 votes
1 answer

assert keyword in python is used for what purpose?

The assert keyword is used while debugging ...READ MORE

answered 1 day ago in Python by Taj
• 340 points
4 views
0 votes
3 answers

What is python? Where it is used?

 Python is develop by Guido Van Rossum ...READ MORE

answered Mar 18 in Python by rajesh kumar
41 views
0 votes
1 answer

What is the use of raw_input function in Python?

raw_input fuction is no longer available in ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
38 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
24 views
+4 votes
6 answers
+1 vote
1 answer

What is the function for Factorial in Python

Easiest way: math.factorial(x) (available in 2.6 and ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,120 points

edited Aug 21, 2018 by Omkar 57 views
0 votes
2 answers

What is the python keyword “with” used for?

Please visit this site to know abt ...READ MORE

answered Aug 31, 2018 in Python by Somesh
27 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.