Reputation: 29
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.
Upvotes: 1
Views: 202
Reputation: 31
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
Upvotes: 0
Reputation: 3572
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
Upvotes: 2
Reputation: 141780
x
is not an index. x
is an element in the list
.
Also, you don't need parentheses around an if
-condition.
>>> 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
Upvotes: 4