Python-Ref > Data structures > Sets > Set introduction
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

Set introduction

Set is a collection which unlike list does not have internal order (there is no xs[1]) and which cannot hold more that one item of the same value. Therefore all values in a set are always unique. In this matter set is similar to a dictionary without values - only keys.
Sets are natural structures for description of many problems for which list are for historical reasons used. For example "pupils of a class" are typical example of data where set should be used - there is no reason to have ordering of pupils at this level and no pupil can be in the class twice.
Sets are designed for fast lookup and union and intersection calculation.
The following example shows few uses of sets.
Expand/Shrink
Zdroj: (sets1-1.py)
  1   text = "Don't panic."
  2   
  3   letters = set()
  4   for letter in text:
  5     letters.add( letter)
  6   
  7   print letters # individual letters used in the above sentence
stdout:
set(['a', ' ', 'c', 'D', "'", 'i', 'o', 'n', 'p', 't', '.'])
Doba běhu: 38.6 ms
Expand/Shrink
Zdroj: (sets1-2.py)
  1   numbers = [1,2,3,2,6,19,2,45,32,0,23,32,19,0,1]
  2   
  3   # the list way
  4   unique = []
  5   for number in numbers:
  6     if number not in unique:
  7       unique.append( number)
  8   print unique
  9   print len( unique)
 10   
 11   # the way of the set
 12   unique = set( numbers)
 13   print unique
 14   print len( unique)
stdout:
[1, 2, 3, 6, 19, 45, 32, 0, 23]
9
set([32, 1, 2, 3, 6, 45, 19, 23, 0])
9
Doba běhu: 19.0 ms