We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,167 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Return a List as a list

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!

6
Contributors
6
Replies
3 Days
Discussion Span
9 Months Ago
Last Updated
7
Views
3e0jUn
Light Poster
36 posts since Jul 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
def get_list():
    myList = ['1','2','a','b']
    return myList

print get_list()
pyTony
pyMod
Moderator
6,309 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26

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
'''
ZZucker
Master Poster
780 posts since Jan 2008
Reputation Points: 342
Solved Threads: 60
Skill Endorsements: 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
griswolf
Veteran Poster
1,176 posts since Apr 2010
Reputation Points: 344
Solved Threads: 262
Skill Endorsements: 1

Note that you can only join a list of strings.

HiHe
Posting Whiz
332 posts since Oct 2008
Reputation Points: 177
Solved Threads: 34
Skill Endorsements: 4

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>

peterparker
Light Poster
29 posts since Jul 2012
Reputation Points: 0
Solved Threads: 1
Skill Endorsements: 0

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
peterparker
Light Poster
29 posts since Jul 2012
Reputation Points: 0
Solved Threads: 1
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0780 seconds using 2.71MB