Difference between tuple and set

Asked

Viewed 230 times

0

I’m working with python and I was wondering what would be the difference between a set(set()) and a tuple(tuple()). I know that both are delimited with '()'.

But I tried to assign a set attribute to a tuple, meaning:

THIS IS MY SET: (OR WHAT I THOUGHT IT WAS...)

basket = ('apple', 'orange', 'banana', 'pineapple', 'pear')

GAVE THE FOLLOWING COMMAND:

basket.discard(2))
print (basket)

When I ran the program I made a mistake... I said:

*line 16: basket.discard(2)

Attributeerror: 'tuple' Object has no attribute 'discard'*

Because you considered my set a tuple?

1 answer

2


Because for python the parentheses delimit a tuple, not a set. If you want a set, you need to use the keys ({, }) or the function set:

basket = {'apple', 'orange', 'banana', 'pineapple', 'pear'}

or

basket = set(('apple', 'orange', 'banana', 'pineapple', 'pear'))
  • But if I use '{}' it looks like Dictionary, in python 3.5.0

  • Yes, to create an empty set you cannot use {} (https://docs.python.org/2/tutorial/datastructures.html#sets). If this is a possibility, then you can always use the function set.

  • So when can I use {} to create a set (which is not clear empty)?

  • 1

    If you wear something like {1, 2, 3} or {'apple', 'banana', 'orange'} you’ll get sets. If you use dictionary syntax ({'apple': 'banana', 'orange': 'pineapple'}) is that you will have a dictionary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.