Reputation: 1056
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
Reputation: 9904
mylist = [f.attribute for f in files] # don't use file, it's the name of a builtin-function
Upvotes: 1
Reputation: 21243
try this
mylist = []
for file in files:
new = file.attribute
mylist.append(new)
Upvotes: 0
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