python - Convert Single integer into a list
There's nothing that will automatically treat an int
as if it's a list of one int
. You need to check whether the value is a list or not:
(a if type(a) is list else [a]) + (b if type(b) is list else [b]) + (c if type(c) is list else [c])
If you have to do this often you might want to write a function:
def as_list(x):
if type(x) is list:
return x
else:
return [x]
Then you can write:
as_list(a) + as_list(b) + as_list(c)
You can use itertools
:
from itertools import chain
a = 1
b = [2,3]
c = [4,5,6]
final_list = list(chain.from_iterable([[a], b, c]))
Output:
[1, 2, 3, 4, 5, 6]
However, if you do not know the contents of a
, b
, and c
ahead of time, you can try this:
new_list = [[i] if not isinstance(i, list) else i for i in [a, b, c]]
final_list = list(chain.from_iterable(new_list))