0

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.

Community
  • 1
  • 1
avacariu
  • 2,780
  • 3
  • 25
  • 25
  • Why do you need it to be a string or a tuple? why can't it be unicode or a list? – aaronasterling Sep 24 '10 at 01:29
  • 2
    I'm not sure how a list comprehension would be useful here, because the code you have doesn't create a list by iteration. You don't even have a `for` loop. – David Z Sep 24 '10 at 01:40
  • The code I have doesn't require a for loop. But if I use the `list(variable` in the list comprehension, it creates a list within a list which isn't what I want _(Although I noticed @Matthew's answer provides a way around it)_. And @Aaron: I don't _need_ it to be a string or a tuple. It's given to me in that format. – avacariu Sep 24 '10 at 03:08

2 Answers2

5

I think you want:

final = [variable] if isinstance(variable, str) else list(variable)
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
2

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
  • 299,747
  • 42
  • 398
  • 622
  • This will give `['id', 'id']` for the examples, since it includes one reference to the string for every letter. – Matthew Flaschen Sep 24 '10 at 01:26
  • 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.) – avacariu Sep 24 '10 at 03:14