0

How can i convert an int into a list containing that int.

I've code:

y=x

Here the odds of x being a int to a list is 95% to 5%. if x is a int then fine. but if x is a list, i had to use:

y=list(x)

but in this case it'll create problem for int.

I can declare x as a list for all the cases. but for just 10% of chances using a list is quite unnecessary.

Is there any other way, if i can convert a int to list (not to string) so that i can use y=list(x) all the time?

RatDon
  • 3,403
  • 8
  • 43
  • 85
  • Are you asking how to do this: if it's a list, don't convert, but if it's an int, convert to a list? In that case, what are you trying to achieve with this? Are you writing a function that aims to accept both lists and integers? – wei2912 Sep 15 '13 at 06:48
  • @wei2912 i'm using y as a backup variable which will update the x later again. and x may contain a list or an int depending on the input given. – RatDon Sep 15 '13 at 06:53
  • In that case, would http://stackoverflow.com/questions/919680/python-can-a-variable-number-of-arguments-be-passed-to-a-function suit your needs more as compared to comparison? – wei2912 Sep 15 '13 at 06:56
  • @wei2912 if i'll use a function, i've to use x as a global or capture the returned variable in x. which will increase the coding lines of the program. which i dont want. – RatDon Sep 15 '13 at 07:00
  • noted, was wondering if you were using a function. Haidro's answer should suit you fine. – wei2912 Sep 15 '13 at 07:02
  • @wei2912 yep. Haidro's working smoothly... :D – RatDon Sep 15 '13 at 07:05

1 Answers1

5

Just put square brackets around it:

y = [x]

If you want to check whether your input is an integer or not, you can use isinstance():

if isinstance(x, int):
    y = [x]
else:
    y = list(x)
TerryA
  • 58,805
  • 11
  • 114
  • 143