when i used for loop for length of the list I got the correct answer.But when I use for loop for I in range list: I got the correct wrong answer enter image description here the first Image shows when value of i is taken.the second image shoes when for loop is take for length of list.what's the problem here? enter image description here
CodePudding user response:
You can use the filter
(to filter negative numbers) and then sum
them -
>>> p = [1,2,-3,4,-4,5,6]
>>> sum(filter(lambda x: x < 0, p))
-7
CodePudding user response:
you are indexing the list like this p[1],p[2],p[-3]...
instead you should iterate through the values
p = [1,2,-3,4,-4,5,6]
t = 0
for i in p:
if i < 0:
t = i
print(t)
or use range(len(p)):
p = [1,2,-3,4,-4,5,6]
t = 0
for i in range(len(p)):
if p[i] < 0:
t = p[i]
print(t)
CodePudding user response:
This is the python code you had in the posted picture.
p = [1,2,-3,4,-4,5,6]
t = 0
for i in p:
if p[i] < 0:
t =p[i]
print(t)
when you use for i in p
, we iterate through the list unlike accessing the list values by their index
If you print each of the value during the loop
for i in p:
print(i)
output:
1
2
-3
4
-4
5
6
Also note that p[-3]
indicates 3rd element from tail of the list
so the values p[i]
in your code are p[1],[2],p[-3],p[4],p[-4],p[5],p[6]
equivalent to 2,-3,-4,-4,5,6
giving you a result of ((-3) (-4) (-4)) = -11