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,750 points
25 views

1 answer to this question.

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,940 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
• 1,040 points
32 views
0 votes
1 answer

assert keyword in python is used for what purpose?

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

answered May 24 in Python by Taj
• 1,040 points
88 views
0 votes
1 answer

What is the patterns package in python used for?

Pattern is a web mining tool in ...READ MORE

answered Jul 31 in Python by Mohammad
• 3,060 points
29 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
67 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 349 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,940 points

edited Aug 21, 2018 by Omkar 160 views
0 votes
3 answers

What is the python keyword “with” used for?

The with statement in Python simplifies exception ...READ MORE

answered Jul 19 in Python by rahul
• 200 points
76 views