Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact Python for() Loop

Tags:

python

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]
like image 576
Biff Avatar asked Jan 14 '23 16:01

Biff


1 Answers

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

like image 70
Ashwini Chaudhary Avatar answered Jan 23 '23 04:01

Ashwini Chaudhary