Ex:
a = []
a.append('Hello')
Which will give the output: ['Hello']
Could you please tell me How to do the same using list comprehension?
If you only have
a = []
a.append('Hello')
as you know, it would be most practical to simply do
a = ['Hello']
But if you want to append multiple 'Hello'
s to the list, you can do it like
a = ['Hello' for _ in range(amount)]
Where the amount
variable should be replaced with the number of 'Hello'
s you want in the list.
Another way to do the above is
a = ['Hello'] * amount
You actually do not need to use list comprehension here. Just simply do:
a=['Hello']
You can do it by doing
a = ['Hello' for i in range(1)]
But it will just lead to more memory allocation than needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.