Python - Set Set iteration

Introduction

As iterable containers, sets can be used with such as len, for loops, and list comprehensions.

Because they are unordered, though, they don't support sequence operations like indexing and slicing:

Demo

for item in set('abc'): print(item * 3)

Result

Set method can often work with any iterable type as well:

Demo

S = set([1, 2, 3]) 
print( S | set([3, 4]) )          # Expressions require both to be sets 
print( S.union([3, 4]) )          # But their methods allow any iterable 
print( S.intersection((1, 3, 5)) )
print( S.issubset(range(-5, 5)) )

Result

Related Topics