I was trying to display/print elements of a list, suppose a = [1,2,3,4,5], using functions. But the code i wrote prints only the first element of the list whereas i needed all the elements of the list to be printed( as in 1 2 3 4 5 but all in new lines). Is there a possibility that recursive function might do the trick. Kindly help with the code.

>>> a = [1,2,3,4,5]
>>> def items(list1):
...   for items in list1:
...     return items
>>> print items(a)

Recommended Answers

print '\n'.join(str(item) for item in a)
Jump to Post

All 3 Replies

print '\n'.join(str(item) for item in a)

Although you have a solution that will print the contents of your list in the desired format, I thought that an explanation of the problem might be useful.

You are calling the function items and passing the list as a parameter. Within this function, you are starting to iterate through this list. However, when the iterator gets the first item in the list, you are telling the function to return it. When Python encounters a return statement, the execution of the code in the function stops and control is passed back to the piece of Python code that called the function, in this case passing the result, the first item in the list, to your print statement. Control does not return to item(). And since there are no more statements in your file, after printing 1, your program is finished.

If the operation of join() is not clear, you might try changing the function items() so that it prints the items within your for loop, simply by changing return to print. Then, in your last line, simply remove the word print.

Another possible way, maybe more clear for beginners ...

def items(list1):
    s = ""
    for item in list1:
        # build up a string
        s += str(item) + '\n'
    return s

a = [1,2,3,4,5]

print items(a)

'''output -->
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.