How to convert an integer to a list in python?

Question:

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].

I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?

Asked By: AviG88

||

Answers:

If you are trying to convert in to string, use str()

>>> str(1234)
'1234'

If you are trying to put your int in a list, use []:

>>> var = 1234
>>> [var]
[1234]

or do:

>>> l = []
>>> l.append(var)
>>> l
[1234]
Answered By: Have a nice day

Here:

a = 1234
lst = []
lst.append(a)

print(lst) #[1234]
Answered By: pakpe

You can just cover it in brackets.

a = 1234
print([a])

Or append()

b = []
b.append(a)

output

[1234]
Answered By: Thavas Antonio

Just cover it with brackets:

a=1243
a=[a]

or create a list and append a

b = []
b.append(a) # or you could do b=[a]
Answered By: RomJan D. Hossain

Well it depends. If you need the int to be a single member of a list then [a] works. If you need each digit in the integer to be an individual member of the list then list(str(a)) will work for you.

Answered By: kelvinmacharia254
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.