000
000

Reputation: 99

How to add multiple variables in list comprehension

I have an if/else clause in a list comprehension and would like to know how I can add multiple variables.

Here's is the code if I use a an if/else statement:

if start_year == end_year:
    years = [start_year]
else:
    years = [start_year, end_year]

Here's how I would like it to look with a list comprehension, however it is incorrect because it tacks on end_year due to the comma separation.

years = [start_year if start_year == end_year else start_year, end_year]

Thanks!

Upvotes: 1

Views: 572

Answers (2)

demented hedgehog
demented hedgehog

Reputation: 7548

years = [year for index, year in enumerate((start_year, end_year))
         if index == 0 or start_year != end_year]

As you wish... it's as ugly as a pig though.

Upvotes: 0

jh314
jh314

Reputation: 27812

The if/else can be consolidated into 1 line:

years = [start_year] if start_year == end_year else [start_year, end_year]

Note that this isn't a "list comprehension" though because there is no for loop.

Upvotes: 4

Related Questions