TransWikia.com

Fill a list with a for loop python

Stack Overflow Asked by DottorBooom on February 23, 2021

Mine is not really a problem but the search for a solution, if any. And knowing this language necessarily exists. I have an integer ‘n’ and an integer ‘p’. What I’m trying to do is divide n into digits, raise them to p and put them in a list. Later I will sum () the list. (Below is the code)

tot = sum([int(x)**p for x in str(n)])

The code works perfectly without any problems, the only thing I miss to add is that at each iteration, ‘p’ must be increase by 1. I have tried many things, and looked at a few other methods, but cannot find the correct syntax for adding this step.
I really hope that some of you can help me find this solution.
Many thanks in advance

3 Answers

Use enumerate to get an index which you can use to increase p by:

tot = sum([int(x) ** (p + i) for i, x in enumerate(str(n))])

If you want to start at p + 1 instead of p + 0, use

tot = sum([int(x) ** (p + i) for i, x in enumerate(str(n), start=1)])

BTW, you don't even need to create the list. Remove the brackets to save some memory:

tot = sum(int(x) ** (p + i) for i, x in enumerate(str(n)))

Correct answer by DeepSpace on February 23, 2021

You can use enumerate() inside your list comprehension to achieve this as:

>>> n = 12345
>>> p = 2

>>> sum([int(x)**(p+i) for i, x in enumerate(str(n))])
16739

enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

You can pass start as 1, if you want to start with p+1 as:

>>> sum([int(x)**(p+i) for i, x in enumerate(str(n), start=1)])
82481

Answered by Anonymous on February 23, 2021

A potential solution based on a for loop should be

tot = []

p = <whatever>

for x in str(n):
   temp = int(x) ** p 
   tot.append(temp)
   p = p + 1

sum(tot)

Answered by mht on February 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP