Create a list of 2 variables

If I have variables x and y , such that:

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

How to 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'] 
+4
source share
3 answers
 z = [x] + (y if isinstance(y, list) else [y]) 

Actually, I would avoid having y , which can be either a string or a list, but: this seems unnecessary.

+10
source
 z = [x] if isinstance(y, list): z.extend(y) else: z.append(y) 
0
source
 import itertools z = itertools.chain(x, y) 
-one
source

Source: https://habr.com/ru/post/1492762/


All Articles