0

Is there a way to express the following code through Python list comprehension?

newlist = []
for i,j in enumerate(old_list):
if i==0:
    newlist.append(j*2+1)
else:
    newlist.append(j*2)
Ash Sharma
  • 470
  • 3
  • 18

2 Answers2

2

Sure, why not?

[j*2+1 if i==0 else j*2 for i, j in enumerate(old_list)]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

I would do it with an inline if, like this:

newlist = [j * 2 + (1 if i == 0 else 0) for i, j in enumerate(old_list)]
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78