Reputation: 21
I can't understand how it works. I have input of :
10 2 3 4 8
And simple code
b = set(input())
print(b)
Returns:
{' ', '3', '1', '2', '8', '0', '4'}
Why I'm getting this ' '
el. and how to get 10 instead of '1'
and '0'
?
Upvotes: 1
Views: 276
Reputation: 2817
Use filter()
with a lambda
function to remove the space elements:
>>> filter(lambda x: x is not " ", [" ", "1", "2", " "])
>>> ['1', '2']
Upvotes: 0
Reputation: 20336
set()
takes an iterable (such as list, tuple, dict, etc.) and makes a set of its items. For example:
x = [4, 5, 6]
y = set(x)
print(y)
#set([4, 5, 6])
A string is iterable, too:
for char in "yay":
print(char)
#Output:
y
a
y
Therefore, a set can convert a string:
x = "yay there"
y = set(x)
print(y)
#set(['a', ' ', 'e', 'h', 'r', 't', 'y'])
If you want each word, use .split()
:
b = set(input().split())
Upvotes: 2