jeudi 1 avril 2021

Create a python list with for-loop and predefined first element

I want to create a list in one line with a for loop as follows:

a = [i for i in range(0, 5)]

In this case a is equal to a = [0, 1, 2, 3, 4]. However I would like to predefine the first element (i.e.: 0) to be 100.

Therefore I am looking for the syntax for generating a = [100, 1, 2, 3, 4] in one line with for-loop.

Something like this:

a = [100, i for i in range(1, 5)]

For this example following would work since we know the first value of the iterator i, but imagine the first iterator value is unknown or can change with some other data. How can I code this?


This could work if I know the first value of i:

a = [100 if i == 0 else i for i in range(0, 5)]

since it is unknown or can change, I need to specify somehow the first loop of the for-loop in if-statement.

Aucun commentaire:

Enregistrer un commentaire