Skip to content

Instantly share code, notes, and snippets.

@pcn
Last active October 10, 2018 12:40
Show Gist options
  • Save pcn/566728082981f30669e0df2362317b2e to your computer and use it in GitHub Desktop.
Save pcn/566728082981f30669e0df2362317b2e to your computer and use it in GitHub Desktop.
Appending to a python list while iterating on it
# This seems like a bad idea, but it also seems to work
In [3]: baselist = range(20)
In [4]: baselist
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [5]: for item in baselist:
...: if item % 2:
...: baselist.append(item + 1)
...: else:
...: print item
...:
0
2
4
6
8
10
12
14
16
18
2
4
6
8
10
12
14
16
18
20
# This is threadsafe and blocking if that's your bag
In [38]: q = Queue.Queue()
In [39]: for i in range(20):
...: q.put(i)
...:
In [40]: while True:
...: if q.empty():
...: break
...: item = q.get()
...: if item % 2:
...: q.put(item + 1)
...: else:
...: print item
...:
0
2
4
6
8
10
12
14
16
18
2
4
6
8
10
12
14
16
18
20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment