1

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

2
  • because you return in the for loop Commented Nov 21, 2015 at 22:13
  • v is a sequence. If v is a string it iterates one character at a time. Commented Nov 21, 2015 at 22:15

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.