0 votes
1 view
in Data Science by (18.3k points)

If I use a while loop for my below code, it is not giving the desired output,

but when i use for loop i am anle to  get the output.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

b = [1, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]

x = 0

Comm = [] #common int in both lists

while x in range(0,len(a)):

    if a[x] in b:

        Comm.append(a[x])

        x += 1

print(Comm)

1 Answer

0 votes
by (36.8k points)
edited by

You need to use the for loop instead of while.

If x goes from the 0 to 6, then a[6] = 13. a[6] is in b, so x becomes 7 and a[7] = 21.

a[7] is not in b, so x doesn't increase. It means that x stops at 7 and doesn't break out of the while loop.

Do check out Data Science with Python course which helps you understand from scratch 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...