If I have an integer like x = 12345, how do I separate that into individual integers 1, 2, 3, 4, 5?

Hi!

You have to convert the integer to an iterable (e.g. a string), then split it into a list, then convert the elements of the list back to integers:

x = 12345
newx = [int(i) for i in list(str(x))]

Regards, mawe

If you wanted to use the digits of an integer, you could convert to a string like mawe suggested and then use the indexed string elements ...

x = 12345
s = str(x)
print s[0]  # 1
print s[1]  # 2
print s[2]  # 3
print s[4]  # 5

print type(s[2])  # <type 'str'>

# to get an integer value use
i = int(s[2])
print i  # 3

Python does make it look easy! Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.