I have a list of objects. In a single line I would like to create a string that contains a specific variable of each object in the list, separated by commas.
Right now I’m able to achieve this using a combination of list comprehensions and map like so:
','.join(map(str, [instance.public_dns_name for instance in instances]))
or using lambda:
','.join(map(str, [(lambda(i): i.public_dns_name)(instance) for instance in instances]))
Each instance object has a “public_dns_name” variable that returns the host name. This returns a string like this:
host1,host2,hos3,host4
Is it possible to achieve the same thing using only the list comprehension?
You can’t use just a list comprehension, you’ll still need to use
join.It’s more efficient to use a generator expression
A list comprehension would look like this:
The difference is that it creates the entire list in memory before joining, whereas the generator expression will create the components as they are joined