Home > Enterprise >  Is it possible to use all while loop inside an array?
Is it possible to use all while loop inside an array?

Time:11-07

We can use for loop inside an array, for example: arr = [i for i in range(10)]

I want to add all the digits of an number into array; can we use the same methodology and implement using while loop?

CodePudding user response:

What you have shown is a list comprehension, not a loop inside an array.

There is no such thing that involves the while keyword.


It's possible to define a generator with a while loop and then use that generator in a list comprehension.

For example, this generates all digits of a non-negative integer (in reverse order):

def digits(n):
    while True:
        n, d = divmod(n, 10)
        yield d
        if n == 0:
            break

arr = [i for i in digits(123)]  # [3, 2, 1]

CodePudding user response:

i want to add all the digits of an number into array can we sue the same methodology and implement using while loop?

No, you cannot do a similar thing with a while loop. The syntax [i for i in range(10)] is called a "list comprehension". If you google these words, you will find more information about how they work.

For the digits of a number, I suggest turning it into a string:

number = 12345
digits = str(number)

Now you can use digits like an array of digit characters:

print(digits[2]) # output: 3
for d in digits:
    print(d)

If you want a list of digits as integers rather than characters:

digits = [int(c) for c in str(number)]
  • Related