1

I have a fairly basic python issue, here's the code:

def LCM(nums): 
    i = max(nums)
    var = 0
    x = 0
    while i>0:
        for x in nums:
            var = var+int(nums[x])%i
        if (var == 0):
            return i
        i=i-1

nums is a list, I think x is the index for that list, and the for statement should iterate through each value in the list as nums[x]. It seems like x should start at the first element of nums, and iterate through each value till nums runs out of values.

Instead, I get list index out of range, I don't understand how this is possible. Is my for syntax screwed up? I can't make this make sense.

2
  • submitting the code destroyed the indents for some reason, I can resubmit if its too confusing Commented Feb 4, 2012 at 21:15
  • 1
    think I fixed it. (You don't need to use [code], simply select the text and hit the {} button above the entry box, or hit control-K). Could you check that the indenting of each line is correct now? Commented Feb 4, 2012 at 21:17

4 Answers 4

4

x is not an index. x is an element in the list.

Also, you don't need parentheses around an if-condition.

Simple demonstration:

>>> nums = [11, 12, 13, 14, 15, 16]
>>> for x in nums:
...     if x % 3 == 0:
...         print x, 'is divisible by three'
...     else:
...         print x
... 
11
12 is divisible by three
13
14
15 is divisible by three
16
Sign up to request clarification or add additional context in comments.

Comments

2

As others said, x is an element of nums. For sake of completeness, if you want to iterate a list and have access to the index, have a look at enumerate()

for i, x in enumerate(nums):
    print i, x #nums[i] == x

2 Comments

You may want to actually call enumerate() in your example ;)
@Johnsyweb what do you mean? :)
0

x already is an element of nums. Replace nums[x] by x.

Comments

0

if you want to travel the elements using it's index, you can use

for x in range (len(nums)):

instead of

for x in nums:

because in your code it is travelling via the index of the i'th value from the list. Like suppose the very first value of the list is 34 and list is of size 5, so according to your code you are trying to travel 34'th index value from the list which is why you getting.

list index out of range

Comments

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.