Cheeter_P
Cheeter_P

Reputation: 71

Difference between {'some_string'} and set('some_string) as key word arguments in Python 3.7+

I am giving feedback to a group of students on an assignment, many of whom are attempting to pass a set as a keyword argument in a function by passing a string in curly braces. When I print (type({'some_string'})) I get class = set. But when I pass the same argument as set('some_string') I get different output.

e.g.

some_random_function (kwarg = {'some_string'})

is different to

some_random_funtion(kwarg = set('some_string'))

can anyone help me understand why?

Upvotes: 2

Views: 64

Answers (2)

Błotosmętek
Błotosmętek

Reputation: 12927

The function set treats its argument as an iterable, and actually iterated over your string, creating a set of letters - you'd get the same result from

set(['s', 'o', 'm', 'e', '_', 's', 't', 'r', 'i', 'n', 'g'])`

What you really wanted is set(['some_string']).

Upvotes: 1

Ch3steR
Ch3steR

Reputation: 20659

That's because {'some_string'} is different from set('some_string')

a= set('some_string')
# {'_', 'e', 'g', 'i', 'm', 'n', 'o', 'r', 's', 't'}

a= {'some_string'}
# {some_string'}

Upvotes: 1

Related Questions