0

I am trying to make a function to iterate over the list. Can anyone let me know and explain that what t is that I am doing wrong?

iplist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']

def ip_addr(addr_list):
    for ip_addresses in addr_list:
        return ip_addresses


test = ip_addr(iplist)

print(test)

I am expecting output:

1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4

However, I am getting the following output:

1.1.1.1

Thanks,

4
  • A return ends the function, and therefore breaks the for-loop Commented Sep 28, 2019 at 21:45
  • How can I fix it? Commented Sep 28, 2019 at 21:49
  • Replace the return ip_address with print(ip_address)? All your function does is loop over the list anyway Commented Sep 28, 2019 at 21:52
  • print is not going to allow test to be set as desired. Commented Sep 28, 2019 at 21:53

4 Answers 4

2

Your function returns the value it encounters in the first iteration of the for loop, causing the loop to terminate immediately. Instead of a loop, join the values of the list together and return them all in one string.

def ip_addr(addr_list):
    return "\n".join(addr_list)
Sign up to request clarification or add additional context in comments.

2 Comments

This is more pythonic
This is also a valid solution!!
0

Your problem is you return at the first iteration of the loop, then you get only the first iteration. Try that:

iplist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']

def ip_addr(addr_list):
    addresses = ""
    for ip_addresses in addr_list:
        addresses += ip_addresses + "\n"
    return addresses  

test = ip_addr(iplist)
print(test)

Comments

0

I am not sure, what you are trying to do, but here are some solutions:

iplist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']

def ip_addr(addr_list):
    for ip_addresses in addr_list:
        yield ip_addresses


test = ip_addr(iplist)

print(*[ip for ip in test])

or just

iplist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
print('\n'.join(iplist))

2 Comments

Yield is cool, but doesn't help here. The list goes in as a list and yield returns the list. Nothing has changed
@MichaelG. I do not know, what he/she is trying to do. Maybe there is more behind it, like some string manipulation?
-1

Above to all valid answers, you can also use a dummy empty list and append inside the values and return that dummy list too.

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.