Change language

Iterating over a set in Python

| |

There are many ways to iterate over a set. Some of these methods provide faster execution than others. Some of these techniques include iteration using for / while loops, comprehension, iterators, and their variations. Let’s take a look at the different ways we can iterate over sets in Python.

Analyzing each method:
To explain how each method / method works, it’s time to type (a randomly generated set ) was calculated for 5 times to get a rough estimate of how long each technique takes to iterate over a given set. random.seed (21) has been added to each script to capture random numbers that are generated each time the program is executed. Using a constant seed helps us determine which method is best for a given randomly generated set.

Method # 1: iterating over the set using a simple for loop.

# Create a set using a string

test_set = set ( " geEks " )

 
# Iterate using a for loop

for val in test_set:

print (val)

Exit:

 kseg E 

Analysis :

# import libraries

from timeit import default_timer as timer

import itertools

import random

  
# Function is being evaluated

def test_func (test_set):

 

for val in te st_set:

_ = val

 
# Driver function

if __ name__ = = ’__main__’ :

 

random.seed ( 21 )

 

for _ in range ( 5 ) :

  test_set = set ( )

 

# generate a set of random numbers

  for el in range ( int ( 1e6 )):

el = random.random ()

test_set.add (el)

 

start = timer ()

  test_func (test_set)

end = timer ()

 

print ( str (end - start))

Exit:

 0.06303901899809716 0.06756918999963091 0.06692574200133095 0.067220498000097 0.06748137499744189 

Method # 2: iterate over a set using an enumerated for loop.

# Create a set with using the string

test_set = set ( "geEks" )

 
# Iterate using a loop enum

for id , val in enumerate (test_set):

print ( id , val)

Exit :

 0 E 1 e 2 k 3 g 4 s 

Analysis :

# import libraries

from timeit import default_timer as timer

import itertools

import random

 
# Function is being evaluated

def test_func (test_set):

 

for id , val in enumerate (test_set):

_ = val

 
# Driver function

if __ name__ = = ’__main__’ :

  

random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

 

  # generate a set of random numbers

  for el in range ( int ( 1e6 )):

el = random.random ()

test_set.add (el)

 

  start = timer ()

test_func (test_set)

end = timer ()

 

  print ( str (end - start))

Exit :

 0.1306622320007591 0.13657568199778325 0.13797824799985392 0.1386374360008631 0.1424286179972114 

Method # 3: iterating over the set as an indexed list

# Create a set using a string

test_set = set ( "geEks" )

 

test_list = list (test_set)

 
# Loop through the set as an indexed list

for id in range ( len (test_list)):

print (test_list [ id ])

Exit:

 gk E se 

Analysis :

# import libraries

from timeit import default_timer as timer

import itertools

import random

 
# Function is being evaluated

def test_func (test_set):

 

test_list = list (test_set)

 

for id in range ( len (test_list)):

_ = test_list [ id ]

 
# Driver function

if __ name__ = = ’__main__’ :

 

random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

 

  # generate a set of random numbers

for el in range ( int ( 1e6 )):

el = random.random ()

  test_set.add (el)

  

start = timer ()

  test_func (test_set)

end = timer ()

 

print ( str (end - start))

Exit :

 0.20036015100049553 0.2557020290005312 0.4601482660000329 0.2161413249996258 0.18769703499856405 

Method # 4: iterating over the set using comprehension and constructor / initializer list a.

Exit :

 kseg E 

Analysis :

# Create a set using a string

test_set = set ( "geEks" )

 
# Iterating Using List-of-Compose

com = list (val for val in test_set)

print ( * com)

# importing libraries

from timeit import default_timer as timer

import itertools

import random

 
# Function evaluated

def test_func (test_set):

 

list (val for val in test_set)

 
# Driver function

if __ name__ = = ’ __main__’ :

 

  random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

 

# generate a set of random numbers

for el in range ( int ( 1e6 )):

el = random.random ()

test_set.add (el)

  

  start = timer ()

test_func (test_set )

end = timer ()

 

print ( str (end - start))

Output :

 0.1662169310002355 0.1783527520019561 0.21661155100082397 0.19131610199838178 0.19931397800246486 

Method # 5: iterating over the set using comprehension.

# Create a set using a string

test_set = set ( " geEks " )

 
# Iterate using list-comprehension

com = [ print (val) for val in test_set]

Exit :

 e E gs k 

Analysis :

# import libraries

from timeit import default_timer as timer

import itertools

import random

  
# Function is being evaluated

def test_func (t est_set):

 

[val for val in test_set]

 
# Driver function

if __ name__ = = ’__main__’ :

 

random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

 

# generate a set of random numbers

for el in range ( int ( 1e6 )):

  el = random.random ()

test_set.add (el)

 

start = timer ()

test_func (test_set)

end = timer ()

 

print ( str (end - start))

Exit :

 0.11386321299869451 0.111869686999853 0.1092844699996931 0.11223735699968529 0.10928539399901638 

Method # 6: brute force and using a map, understanding list

# importing libraries

from timeit import default_timer as timer

import itertools

import random

 
# Function is being evaluated

def test_func (test_set):

 

[ map ( lambda val: val, test_set)]

 
# Driver function

if __ name__ = = ’ __main__’ :

 

random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

 

  # generate a set of random numbers

  for el in range ( int ( 1e6 )):

el = random.random ()

test_set.add (el)

 

start = timer ()

test_func (test_set)

end = timer ()

 

# Function is evaluated

def test_func (test_set):

 

[ map ( lambda val: val, test_set) ]

 
# Driver function

if __ name__ = = ’__main__’ :

  

random.seed ( 21 )

for _ in range ( 5 ):

test_set = set ()

  

# gene

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically