How do I rearrange the following code into a simplified list comprehension?
for i in xrange(len(list)):
if list[i].startswith('c'):
list[i] = prefix + list[i]
I tried the following but it did not seem to work:
[prefix + list[i] for i in xrange(len(list)) if list[i].startswith('c')]
The following throws me off:
list[i] = prefix + list[i]
You need to use the ternary operator
here:
[prefix + i if i.startswith('c') else i for i in my_list]
Note that this doesn't changes the original my_list
, it simply returns a new list.
You can simply asssign the list comprehension back to my_list
to achieve that:
my_list=[prefix + i if i.startswith('c') else i for i in my_list]
PS: Don't use list
as a variable name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With