Tom Collins
Tom Collins

Reputation: 179

How to append a list to a list created by a function in Python

Okay, I have a list that looks like this

OldList = [1000, 2000, 3000, 4000, 5000]

And I want to run all members of that list through a function called ListMultiply, like so

NewList = ListMultiply("/listfile/" + oldList]

How do I do this without concatenating string/list? Thanks.

Upvotes: 2

Views: 219

Answers (2)

utdemir
utdemir

Reputation: 27216

You should concatenate the string/list somewhere("".join or str.format would be better anyway), but I think you look something like:

>>> OldList = [1000, 2000, 3000, 4000, 5000]
>>> def f(x):
...     return x*2
... 
>>> OldList = [1000, 2000, 3000, 4000, 5000]
>>> NewList = [f("listfile/" + str(i)) for i in OldList]
>>> NewList
['listfile/1000listfile/1000', 'listfile/2000listfile/2000', 'listfile/3000listfile/3000', 'listfile/4000listfile/4000', 'listfile/5000listfile/5000']

Upvotes: 0

yan
yan

Reputation: 20982

NewList = [ListMultiply("/listfile/"+str(e)) for e in OldList]

The above will create a new list by adding the string "/listfile/" to the string representation of each element and passing the result to ListMultiply().

Upvotes: 5

Related Questions