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)
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)
Sure, why not?
[j*2+1 if i==0 else j*2 for i, j in enumerate(old_list)]
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)]