Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic, possibly one liner, to iterate over a string within a list? [duplicate]

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?.

like image 475
Aaron Avatar asked Jan 28 '26 22:01

Aaron


1 Answers

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
like image 50
arshajii Avatar answered Feb 01 '26 23:02

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!