Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of 2 variables

If I have variables x and y, such that:

  • x is always a string
  • y can either be a string or a list of strings

How can I create a list z == [x, <all elements of y>]?

For instance:

x = 'x'
y = 'y'
# create z
assert z == ['x', 'y']
x = 'x'
y = ['y', 'y2']
# create z
assert z == ['x', 'y', 'y2']
like image 364
user1008636 Avatar asked Jan 12 '23 21:01

user1008636


1 Answers

z = [x] + (y if isinstance(y, list) else [y])

Generally I'd avoid having a y that could be either a string or a list, though: it seems unnecessary.

like image 62
David Robinson Avatar answered Jan 16 '23 01:01

David Robinson