Ravi Mehta
Ravi Mehta

Reputation: 485

Python For Loop to List

I have a beginner Python question. I was wondering if it was possible to take the results of a for loop that came from a list and then turn it back into a list again. I've got code that looks something like this.

for a in mylist:
    result = q.myfunction(a)
    print q, a

I would like the results of this list to be something that I can use to create a table in my database. I am using Python 2.7 on Windows 7. I have looked through the documentation from python on for loops, and looked through questions on stack exchange, and I am still confused.

Upvotes: 0

Views: 465

Answers (3)

abarnert
abarnert

Reputation: 366133

Sure.

Just printing things out obviously doesn't append them to a list. But calling the append method on a list does, as explained in the Lists section of the tutorial. For example:

mynewlist = []
for a in mylist:
    result = q.myfunction(a)
    print q, a
    mynewlist.append(result)

If all you want to do is create a new list, no other side effects, a list comprehension makes it even simpler. This code:

mynewlist = [q.myfunction(a) for a in mylist]

… does the same as the above, but without the print.

Upvotes: 3

Dunes
Dunes

Reputation: 40893

If you're used to using for loops then you can do the following:

results = []
for a in mylist:
    result = q.myfunction(a)
    results.append(result)

However, the idiomatic way to do something like this in python is to use what's known as a list comprehension. List comprehensions are a way of producing new lists from the elements of others lists. For example, the following has exactly the same effect as the above for loop.

results = [q.myfunction(a) for a in mylist]

Upvotes: 2

simonzack
simonzack

Reputation: 20948

Is this what you want?

[q.myfunction(a) for a in mylist]

It's called a list comprehension.

Upvotes: 1

Related Questions