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?
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]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
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]
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.
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?
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]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
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]
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.