Paul Viorel
Paul Viorel

Reputation: 252

Is it the best way to create an array from a list of objects?

I have a list of objects stored in socialmedias variable. One parameter of SocialMedia class is called username. I want to create an array with all usernames from that list of objects socialmedias and I want to be sure I use the best way.

socialmedias = [obj1, obj2, obj3, ..., objN]
usernames = []

for sm in socialmedias:
    usernames.append(sm.username)
print(usernames)
>> [username1, username2, username3, ..., usernameN]

Is there any other way to do it in less line of codes I used above?

Upvotes: 0

Views: 52

Answers (4)

0x0fba
0x0fba

Reputation: 1620

Using a function.

list(map(lambda sm: sm.username, socialmedias))

Upvotes: 0

Willy Lutz
Willy Lutz

Reputation: 314

By memory I would say by using list comprehension:

socialmedias = [obj1, obj2, obj3, ..., objN]
usernames = [sm.username for sm in socialmedias]

print(usernames)

It should do the work.

Upvotes: 0

LoLo2207
LoLo2207

Reputation: 118

You could do

usernames = [sm.username for sm in socialmedias] 

From: Extract list of attributes from list of objects in python

Upvotes: 0

aleksandarbos
aleksandarbos

Reputation: 625

yes there is, you can use list comprehension like:

usernames = [sm.username for sm in socialmedias]

Upvotes: 2

Related Questions