Python - Set literals in Python 3.X and 2.7

Introduction

In Python 3.X and 2.7, the following are equivalent:

set([1, 2, 3, 4])   # Built-in call (all) 
{1, 2, 3, 4}        # Newer set literals (2.7, 3.X) 

Sets are like valueless dictionaries, the items in set behave much like a dictionary's keys.

Here's what sets look like in 3.X; it's the same in 2.7, except that set results display with 2.X's set([...]) notation.

C:\code> c:\python33\python 
>>> set([1, 2, 3, 4])            # Built-in: same as in 2.6 
{1, 2, 3, 4} 
>>> set('test')                  # Add all items in an iterable 
{'t', 'e', 's', 't'} 
>>> {1, 2, 3, 4}                 # Set literals: new in 3.X (and 2.7) 
{1, 2, 3, 4} 
>>> S = {'t', 'e', 's', 't'} 
>>> S 
{'t', 'e', 's', 't'} 
>>> S.add('test')                # Methods work as before 
>>> S 
{'t', 'e', 's', 'test', 't'} 

Demo

S1 = {1, 2, 3, 4} 
print( S1 & {1, 3} )                  # Intersection 
print( {1, 5, 3, 6} | S1 )            # Union 
print( S1 - {1, 3, 4} )               # Difference 
print( S1 > {1, 3} )                  # Super set
# from  w  w w . j av a  2s .c  o m

Result

{} is still a dictionary in all Pythons.

Empty sets must be created with the set built-in, and print the same way:

Demo

S1 = {1, 2, 3, 4} 
print( S1 - {1, 2, 3, 4} )            # Empty sets print differently 
print( type({}) )                     # Because {} is an empty dictionary 
# from   www. j  a  v a 2s .  co  m
S = set()                    # Initialize an empty set 
S.add(1.23) 
print( S )

Result

More set operation

Demo

print( {1, 2, 3}.union([3, 4]) )
print( {1, 2, 3}.union({3, 4}) )
print( {1, 2, 3}.union(set([3, 4])) )
print( {1, 2, 3}.intersection((1, 3, 5)) )
print( {1, 2, 3}.issubset(range(-5, 5)) )

Result

Related Topic