How could I make the return command in Python return a list AS a list, and not as a 'programmer' list? For example,

for line in list:
    return (line)

But for some reason it only returns the first element in the list, for example:

myList = ['1','2','a','b']
for line in myList:
    return (line)

>>>
1
>>>

And that's all I get. Any form of help is appreciated!

Recommended Answers

All 6 Replies

def get_list():
    myList = ['1','2','a','b']
    return myList

print get_list()

Maybe you mean something like this:

def create_string_list(mylist):
    string_list = ""
    for item in mylist:
        string_list += str(item) + '\n'
    return string_list


mylist = ['1','2','a','b']
string_list = create_string_list(mylist)
print(string_list)

'''result>>
1
2
a
b
'''
commented: Thanks! That was exactly what I wanted +1

If you want to convert lists (tuples) to strings using the same string between each item, such as ZZucker suggests, you should use the join method on a string, as for instance:

my_list = ['one', 'two', 'three', 'the end']
print('\n'.join(my_list))

which results in this output:

one
two
three
the end

Note that you can only join a list of strings.

myList = ['1','2','a','b']

mylist = ' '.join(list for list in myList)
print "['" + mylist.replace(' ',"','") + "']"

output:

PS C:\Users\rk\pythonprograms> python lists.py
['1','2','a','b']
PS C:\Users\rk\pythonprograms>

f you are looking to print individual element:

myList = ['1','2','a','b']

for mylist in myList:
    print mylist:
   output: 
    PS C:\Users\rk\pythonprograms> python lists.py
1
2
a
b
Be a part of the DaniWeb community

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