Strings are iterable. Lists are iterable. And with a List of Strings, both the List and the Strings can be iterated through with a nested loop.
For Example:
input = [ 'abcdefg', 'hijklmn', 'opqrstu']
for item in input:
for letter in item:
print letter
Out:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
It seems we can then iterate within the iteration over the string, i.e. iterate over each letter of 'abcdefg'. Is there a more pythonic way to iterate as above, possibly in one statement?
I've re-read through Learning Python Chapter 4, Chapter 1 of the Python Cookbook, and looked here in python: iterate over each string in a list, and here Displaying and iterating a list within a string?.
You can use itertools.chain.from_iterable():
>>> from itertools import chain
>>> input = ['abcdefg', 'hijklmn', 'opqrstu']
>>>
>>> for letter in chain.from_iterable(input):
... print letter
...
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With