Lucifer N.
Lucifer N.

Reputation: 1056

Python iterating over a list to add items to another list?

So I am getting a list of items from a MySQL database, working with Python, Flask, Flask-SQLAlchemy. I am already incrementing rows of this list like this:

for file in files:
        file.last_viewed_time = datetime.utcnow()
    db.session.commit()

But I want to extract one more thing from this list (files), a list of another attribute. How can I add these to a new list, something like:

mylist = []

for file in files:
        new = file.attribute
        add new to mylist  

Or is this a convoluted way of doing it, can I copy these values in a better way?

Upvotes: 1

Views: 146

Answers (3)

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

mylist = [f.attribute for f in files] # don't use file, it's the name of a builtin-function

Upvotes: 1

Neel
Neel

Reputation: 21243

try this

mylist = []

for file in files:
        new = file.attribute
        mylist.append(new)

Upvotes: 0

falsetru
falsetru

Reputation: 369094

Use list.append:

mylist = []

for f in files:
    new = f.attribute
    mylist.append(new)

Or using list comprehension:

mylist = [f.attribute for f in files]

Upvotes: 4

Related Questions