0

I am new to python. I need to iterate over words one by one from a list. But i can only iterate through each letters in each words vertically.

l = ['abcd efgh ijkl']

for i in l:
    for j in i:
        print(j)

Output:

a
b
c
d
 
e
f
g
h
 
i
j
k
l

Expected output:

abcd
efgh
ijkl
theherk
  • 6,954
  • 3
  • 27
  • 52
Kishan
  • 334
  • 2
  • 16
  • 1
    Does this answer your question? [How to iterate over each string in a list of strings and operate on its elements?](https://stackoverflow.com/questions/20968823/how-to-iterate-over-each-string-in-a-list-of-strings-and-operate-on-its-elements) – l'L'l Jun 16 '23 at 16:52

5 Answers5

5

Use split() to split the string via spaces.

l = ["abcd efgh ijkl"]

for i in l:
    for j in i.split():
        print(j)
Michael Cao
  • 2,278
  • 1
  • 1
  • 13
1

You have a single element (the string 'abcd efgh ijkl') in the list, you need to split it:

l = ['abcd efgh ijkl']
for i in l:
    # this will split on whitespace,
    # you can split explicitly on space only split(' ')
    for j in i.split():                     
        print(j)
khachik
  • 28,112
  • 9
  • 59
  • 94
0
l = ['abcd efgh ijkl']
for word in l[0].split(" "):
    print(word)

Or for many strings with words:

l = ['abcd efgh ijkl', 'word1 word2', 'word3 word5']
for string in l:
    for word in string.split(" "):
        print(word)
-3

You have an additional step in your code, try:

l = ['abcd efgh ijkl']
for i in l:
    print(i)
itprorh66
  • 3,110
  • 4
  • 9
  • 21
-3

Why are you using a second for loop? The words must be within quotes.

l = ['abcd', 'efgh', 'ijkl']

for i in l:
    print(i)

In ipython

In [110]: l = ['abcd', 'efgh', 'ijkl']
     ...:
     ...: for i in l:
     ...:     print(i)
     ...:
abcd
efgh
ijkl
UNagaswamy
  • 2,068
  • 3
  • 30
  • 35