Reputation: 242
I have a list of 'id' and their vaules. I am trying to loop through the list and print out the values of each 'id'. It has to be done in one line though. I am struggling to come up with the solution though. The closest I have gotten is below:
ls = [
{'id':'1'},{'id':'2'},{'id':'3'},{'id':'4'},{'id':'5'},
{'id':'6'},{'id':'7'},{'id':'8'},{'id':'9'},{'id':'10'},
{'id':'11'},{'id':'12'},{'id':'13'},{'id':'14'},{'id':'15'},
{'id':'16'},{'id':'17'},{'id':'18'},{'id':'19'},{'id':'20'},
{'id':'21'},{'id':'22'},{'id':'23'},{'id':'24'},{'id':'25'}
]
print([(ls[num]['id']) for num in range(25)])
This gives me the values for each 'id' in the list which is great! But, it returns them all in a list. I need them all on separate lines. Like so:
'1'
'2'
'3'
'4'
'5'
Any ideas how I can go about this? It has to be done with a one-liner.
Upvotes: 0
Views: 27
Reputation: 45741
If you really want a one liner, you can make use of unpacking and the sep
argument of print
:
print(*[(ls[num]['id']) for num in range(25)], sep="\n")
*
unpacks the elements into the arguments of print
, then sep
tells print
to add a newline between each printed argument.
I think this would be neater by making use of a full for
loop though, with separate print
s:
for elem in [(ls[num]['id']) for num in range(25)]:
print(elem)
I'd personally only use that one-liner for quick debugging.
Upvotes: 1