1

How do I loop over a list in Python. I tried using for ch in sample_list but it only goes through one item in the list.

sample_list = ['abc', 'def', 'ghi', 'hello']
for ch in sample_list:
       if ch == 'hello':
              return ch

How do I make it work?

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
Arsalan Ali
  • 29
  • 1
  • 5

3 Answers3

2

return terminates the function, to avoid this you could use print (or yield; which creates a generator):

>>> sample_list = ['abc', 'def', 'ghi', 'hello']
>>> for ch in sample_list:
...     if ch == 'hello':
...          print(ch)
... 
hello

However, for this particular example you should be using any() or list.count() (depending on exactly what you want to do next):

>>> any(item == 'hello' for item in sample_list)
True
>>> sample_list.count('hello')
1
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
1

as @Chris_Rands says, you can use yield.

def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    for ch in sample_list:
        if ch == 'hello':
            yield ch

You should be aware that the yield return a generator in place of a list.

However you can also create a new list with results.

def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    results = []
    for ch in sample_list:
        if ch == 'hello':
            result.append(ch)

    return results
Diblo Dk
  • 585
  • 10
  • 26
0

Try this

sample_list = ['abc', 'def', 'ghi', 'hello']
out = []
for ch in sample_list:
    if ch == 'hello':
        out.append(ch)

return out

Apparently return statement is mostly used in a function to return the control to the caller Function Unless you are using it within a function. You would rather use print function

I hope this helps

shaddyshad
  • 217
  • 4
  • 15
  • can you see the diff between yours and @Diblo's solution on returning? change that and i will vote it up – Ari Gold Dec 09 '16 at 16:04
  • 1
    @AriGold , scrapped that part off, hadn't seen that yet - Thanks – shaddyshad Dec 12 '16 at 07:36
  • whats happens if that is your list: ['hello', 'abc', 'def', 'ghi', 'hello'], what would be the return? change that issue please – Ari Gold Dec 12 '16 at 09:24
  • 1
    so we need to append all the occurrences of the word 'hello' to a say a list. Got that. i think it would be the same as the @Diblo's solution – shaddyshad Dec 12 '16 at 12:23