Iterate over a set in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about iterating/traversing over a set in Python 3.x. Or Earlier.

It is an unordered collection of objects without any duplicates. This can be done by enclosing all the elements within curly braces. We can also form sets by using type casting via a keyword “set”.

Method 1 − Using iterables without indexes

Example

set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value in set_inp:
   print(value, end='')

Method 2 − Using indexed access by converting to list type

Example

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(0,len(set_inp)):
   print(set_inp[value], end='')

Method 3 − Using the enumerate type

Example

set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value,char in enumerate(set_inp):
   print(char, end='')

Method 4 − Using negative index by converting to list type

Example

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(-len(set_inp),0):
   print(set_inp[value], end='')

The above 4 methods yeilds the following output.

Output

plsrainuto

Method 5 − Using slicing after converting to list type

Example

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set

for value in range(1,len(set_inp)):
   print(set_inp[value-1:value], end='')
print(set_inp[-1:])

Output

['p']['l']['s']['r']['a']['i']['n']['u']['t']['o']

Conclusion

In this article, we learned about iteration/traversal over a set data type. Also, we learned about various implementation techniques.

raja
Published on 07-Aug-2019 11:38:18
Advertisements