Reputation: 69
I'm comparing between set of string and set of list of string. The results appear inconsistent and are puzzling to me.
For example, while set('3') == set(['3'])
is returning True, set('003') == set(['003'])
is returning False.
Could anyone help to explain why is this the case?
Upvotes: 0
Views: 58
Reputation: 4215
set('003')
creates an entry for every unique item in that string
(list
of chars
), so it returns {'3', '0'}
and it's equal to set(['0','0','3'])
.
While set(['003'])
creates an entry for each item of the list
, so it returns {'003'}
Upvotes: 2
Reputation: 3297
To get the full explanation, you can print the set()
for every example.
>>>set('3')
{'3'}
>>>set(['3'])
{'3'}
>>>set('003')
{0, 3}
>>>set(['003'])
{'003'}
set('003')
the string is a list of characters, that is why it unzipped it and added 0 and 3 as items. set(['003'])
here the list has on item which is the 003
, so it will unzip this item and add it.
set()
will unzip the list items and add them as its items. For more in deep info please read the offical docs
Upvotes: 2
Reputation: 15872
First case:
>>> set('3') == set(['3'])
True
>>> set('3')
{'3'}
>>> set(['3'])
{'3'}
Second case:
>>> set('003') == set(['003'])
False
>>> set('003')
{'0','3'}
>>> set(['003'])
{'003'}
When you pass strings to tuple
, set
, list
etc. each character of the string is viewed as one element of that data structure. As you may know, set
are collection of unordered, unique elements. So when you call set
on '003'
, it is creating a set, and tries putting one character at a time in that set. First character would be 0
, then 3
, then another 3
, but as their is repetition, one of the 3
s is ignored. So you get: {'0','3'}
. In case of a string
inside a list
, the entire string is viewed as an element, so the set gets only one element, that is {'003'}
.
You can check a few more examples:
>>> tuple('abc')
('a','b','c')
>>> list('abc')
['a','b','c']
Upvotes: 1
Reputation: 204
Because set(['003'])
returns {'003'}
, and set('003')
- {'0', '3'}
.
Upvotes: 1