0

As what mentioned in the Title, if both of them serve for the same purpose? Most of the time i will chose to use list, and i don't know when is a better time to use set.add() function.

I try both of them and give me the exact same result... Personally feel list is better. What do you guys think?

a = set()
a.add('a1')
a.add('a2')
a.add('a3')
for ele in a:
    print ele

b = []
b.append('a1')
b.append('a2')
b.append('a3')
for ele in b:
    print ele

Please advise...

Pi-Turn
  • 137
  • 4
  • 17
  • Look up the definition of a set. –  Jun 10 '14 at 12:55
  • 2
    OK, Thanks @Edgar Aroutiounian for the suggestion. I found a very good thread to describe this also [add vs list thread](http://stackoverflow.com/questions/2831212/python-sets-vs-lists) – Pi-Turn Jun 10 '14 at 13:10

1 Answers1

2

In terms of general data structures, a set structure tends to allow only one element of each value whereas a list may have more than one of each.

In other words, the pseudo-code set.add(7) executed twice results in the set containing the single element 7 (or an error if it considers adding the same element twice to be invalid).

Using a list instead of a set would result in two elements, both being 7.


For Python specifically, adding duplicates to a set is not an error but it still plainly only allows one of each:

>>> s = set()
>>> s.add(1)
>>> s.add(1)
>>> s.add(2)
>>> s
set([1, 2])

The list on the other hand allows multiples:

>>> l = list()
>>> l.append(1)
>>> l.append(1)
>>> l.append(2)
>>> l
[1, 1, 2]

The reason why you didn't see a difference is simply because you added three unique items to the list and set. In that context, they act the same. Behaviour only diverges when you add duplicate items.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953