-1

I am learning python , I leaned in one tuturial that set doesn't allow mutable objects so mutable objects are list I think ?

When i tried this

x = set(["Perl", "Python", "Java"])

it's working fine.

when I tried

cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))

it also working but when i tried this

citiess = set((["Python","Perl"], ["Paris", "Berlin", "London"]))

it's giving error ? so why it's giving error and if it's a list then why first code is running when that also have list??

Please don't redirect question its not same like 'how to construct a set out of list items'

  • 1
    This is not duplicate –  Sep 29 '16 at 17:32
  • a list cannot be a set element; this will fail:`set().add([1,2,3])` – VPfB Sep 29 '16 at 17:35
  • 1
    @User123999 It is a duplicate because of the confusion as what `set(["Perl", "Python", "Java"])` is actually doing.. it is constructing a set from a list of items. Perhaps if you changed `set(["Perl", "Python", "Java"])` to `{"Perl", "Python", "Java"}` and `set((["Python","Perl"], ["Paris", "Berlin", "London"]))` to `{(["Python","Perl"], ["Paris", "Berlin", "London"])}` it will become clear why the first works and the second does not. Note that the `{...}` is the set literal notation. – SethMMorton Sep 29 '16 at 17:41

1 Answers1

3

Sets don't allow mutable elements*, but in set(["Perl", "Python", "Java"]), the list is not an element. The elements of the list are used as the elements of the new set, and the elements of the list are immutable.

*specifically, elements which are mutable in ways that affect == comparisons.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Sorry I am really noebie in python , can you please give some little time to explain this , it would be great help "the list is not an element. The elements of the list are used as the elements of the new set, and the elements of the list are immutable." –  Sep 29 '16 at 17:33
  • In the first example, you create a set of three strings. The `set()` constructor creates a set based on whatever is passed as its argument. It iterates over that list and adds things from it to your set. In the 2nd example, you’re working on tuples, which are legal set elements. In the third one however, you would end up with a set of 2 lists, which is not allowed. – Chris Warrick Sep 29 '16 at 17:40