1

I'm writing a for loop in Python and I'd like to iterate over a mix of single objects and flattened lists (or tuples) of objects.

For example:

a = 'one'
b = 'two'
c = [4, 5]
d = (10, 20, 30)

I'd like to iterate over all of these in a for loop. I was thinking a syntax like this would be elegant:

for obj in what_goes_here(a, b, *c, *d):
  # do something with obj

I looked in itertools for what_goes_here and I didn't see anything, but I feel I must be missing something obvious!

The closest I found was chain but I'm wondering if anything exists that would leave my example unchanged (replacing what_goes_here only).

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
nonagon
  • 3,271
  • 1
  • 29
  • 42

2 Answers2

2

You can do this, but you have to use Python 3.5 or higher for the expanded unpacking syntax. Put all the arguments into a container (like a tuple) then send that container to itertools.chain.

>>> import itertools
>>> a = 'one'
>>> b = 'two'
>>> c = [4, 5]
>>> d = (10, 20, 30)
>>> list(itertools.chain((a, b, *c, *d)))
['one', 'two', 4, 5, 10, 20, 30]
>>> list(itertools.chain((a, *c, b, *d)))
['one', 4, 5, 'two', 10, 20, 30]
>>> list(itertools.chain((*a, *c, b, *d)))
['o', 'n', 'e', 4, 5, 'two', 10, 20, 30]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0
import collections, itertools

a = 'one'
b = 'two'
c = [4, 5]
d = (10, 20, 30)
e = 12

l = [a, b, c, d, e]

newl = list(itertools.chain(*[x if isinstance(x, collections.Iterable) and not isinstance(x, str) else [x] for x in l]))
Al Johri
  • 1,729
  • 22
  • 23