1
def tomtoCm(add):
    assert add > 0
    return add * 2.54



numbers = [4, 1, 20]

def numbersToCm(numbers):
     
    for i in numbers:
        convert = tomtoCm(numbers[0,1,2])
        print(convert)

numbersToCm(numbers)

I am struggling to * 2.54 to all my numbers in my list. I have tried using len and range, but I can't seem to do it quite right. If I for example write [0] the program prints out 10.16 three times. It won't iterate through my whole list

2
  • You never modify the list. And what is the purpose of tomtoCm(numbers[0,1,2])? Commented Oct 4, 2021 at 11:14
  • The code seem to be a bit of a mess, first of all, you are looping through the numbers list, but repeating the same items. Hence, you need to iterate through i instead of [0,1,2]. Also, I don't see why you need a seperate function for (tomtoCm) and (numbersToCm) when both can be made into one, making the code much simpler Commented Oct 4, 2021 at 11:19

1 Answer 1

2

With a for-in loop, you iterate over the list's elements, not its indexes. I.e.:

for i in numbers:
    convert = tomtoCm(i)
    print(convert)

Having said that, the more idiomatic approach would probably be to use a list comprehension:

updated_list = [tomtoCm(i) for i in numbers]
print(updated_list)
Sign up to request clarification or add additional context in comments.

3 Comments

To add to this, you can also easily modify this list comprehension to skip the first function entirely as well (something like updated_list = [ i * 2.54 for i in numbers])
@ZaidAlShattle True 'dat. I wanted to keep OP's original function that has the added assertion, but it would probably be "cleaner" python to unwrap it
Makes sense! Just wanted to add that note in case OP saw it. Cheers buddy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.