You are creating a set
below:
numbers = {6, 5, 3, 8, 4, 2, 5, 4, 11}
whereas the below one will create a list
:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
The difference is that, set
datastructure in python is equivalent to one in mathematics, where elements are unordered and unindexed. No duplicates are allowed.
Incase of a list
, however, elements are ordered, indexed and duplicates are allowed.This is the reason, why you see difference in output for the program you have written.
You can always check the type of an object by using type
function.
In the below code snippet, you can see that a set is created and the elements in it.
>>> numbers = {6, 5, 3, 8, 4, 2, 5, 4, 11}
>>> type(numbers)
<type 'set'>
>>> print numbers
set([2, 3, 4, 5, 6, 8, 11])
Code snippet for list below:
>>> numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
>>> type(numbers)
<type 'list'>
>>> print numbers
[6, 5, 3, 8, 4, 2, 5, 4, 11]
In general, notations like {}
for set
and []
for list
are very useful when used with comprehension techniques. Though they can very well be used the way you have done, you can also use set()
or list()
to make the code a little more readable for Python beginners.