views:

50

answers:

2

I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list.

Essentially, I want to transform the following into a list comprehension.

variable = 'id'
final = []
if isinstance(variable, str):
    final.append(variable)
elif isinstance(variable, tuple):
    final = list(variable)

I was thinking something along the lines of the following (which gives me a syntax error).

final = [var for var in variable if isinstance(variable, tuple) else variable]

I've seen this question but it's not the same because the asker could use the for loop at the end; mine only applies if it's a tuple.

NOTE: I would like the list comprehension to work if I use isinstance(variable, list) as well as the tuple one.

+2  A: 

You just need to rearrange it a bit.

final = [var if isinstance(variable, tuple) else variable for var in variable]

Or maybe I misunderstood and you really want

final = variable if not isinstance(variable, tuple) else [var for var in variable]
Mark Ransom
This will give `['id', 'id']` for the examples, since it includes one reference to the string for every letter.
Matthew Flaschen
Thanks! Your second one seems to be what I want. I accepted Matthew's because it was a tad shorter and simpler (because he did `list(variable)` rather than `[var for var in variable]` although they amount to the same thing.)
vlad003
+3  A: 

I think you want:

final = [variable] if isinstance(variable, str) else list(variable)
Matthew Flaschen
Thanks! That's exactly what I was looking for.
vlad003