Someguy
Someguy

Reputation: 11

Why does a for loop in a function iterate only one letter of a string in python?

Every time I run a function with a for loop in it,the for loop only iterates through the first character.An example

def tin(v):            
    for x in v:
        return x
print tin("hello")

In this case it would be the first letter

Upvotes: 1

Views: 1284

Answers (2)

Alex Huszagh
Alex Huszagh

Reputation: 14584

You should look at a Python tutorial or look up what the return statement means in Python.

return leaves the current function call with the expression list (or None) as return value. Simple Statements

In short, it will evaluate the function until a return statement is found, which happens to be the first item in the loop. This is useful if you intend to break the loop early on a certain condition, but not in this case.

A better example could be:

>>> def tin(v):
...     values = []
...     for letter in v:
...         values.append(v)
...     return values
>>> tin("Hello")
['H', 'e' 'l', 'l', 'o']

This can be condensed down to (using list comprehension):

>>> def tin(v):
...     return [i for i in v]
>>> tin("Hello")
['H', 'e' 'l', 'l', 'o']

If you wish to use a generator (which then can be evaluated later, use yield).

>>> def tin (v):
...     for letter in v:
...         yield letter

>>> list(tin("Hello"))
['H', 'e' 'l', 'l', 'o']

This can be condensed down to (using a generator expression):

>>> def tin(v):
...     return (i for i in v)
>>> gen = tin("Hello")
<generator object <genexpr> at 0x7fbe060534c8>
>>> list(gen)
['H', 'e' 'l', 'l', 'o']

Upvotes: 1

Because you are using return so it's returning only the first result, which is "h".

Try using yield to return a generator or just save each letter to a list so you can then iterate over it to do whatever you want to.

Using yield:

def tin(v):            
    for x in v:
        yield x

for letter in tin("hello"):
    print letter

Using a list inside the function:

def tin(v):
    letters = list()           
    for x in v:
        letters.append(x)
    return letters

for letter in tin("hello"):
    print letter

Using a list comprehension:

def tin(v):
    return [letter for letter in v]

for letter in tin("hello"):
    print letter

Output for those examples is the same:

h
e
l
l
o

Upvotes: 1

Related Questions