Home > other >  Why replacing in range "(len(list)" with "in list" changing output of the progra
Why replacing in range "(len(list)" with "in list" changing output of the progra

Time:12-01

I was writing code for a program which performs intersection of elements in the two lists, which means the common elements in both the lists are returned. changing "in _list" with "in range (len(list))" used for traversing in one of the list changed the output of the function

Input code 1:

def inn(nums1,nums2):
            a=set()
            b={}
            for i in range(len(nums2)):
                    b[nums2[i]]="h"
            print (b)
            for j in nums1:    #**calling elemnts by in**
                    if j in b:
                        print(j)
                        a.add(j)
       
            return a
inn([1,2,2,1],[2,2])

Output code 1(correct):

    {2: 'h'}
    2
    2
    {2}

Input code 2:(with changed method in 2nd loop):

def inn(nums1,nums2):
            a=set()
            b={}
            for i in range(len(nums2)):
                    b[nums2[i]]="h"
            print (b)
            for j in range(len(nums1)):  #**calling elements by range**
                    if nums1[j] in b:
                        print(nums1[j])
                        a.add(j)
            return a
inn([1,2,2,1],[2,2])

output code 2(Incorrect):

    {2: 'h'}
    2
    2
    {1, 2}

CodePudding user response:

In the first listing, j is an element of the list num1. In the second listing, j is used as the index of an element in the list num1.

You understood the difference when you replaced

                if j in b:
                    print(j)

in the first listing with

                if nums1[j] in b:
                    print(nums1[j])

in the second listing.

But you forgot the difference in the next line, which is the same in both listings. It should be

                    a.add(nums1[j])

in the second listing.

Then both outputs would be the same.

CodePudding user response:

You can simplify your inn function with the built in set operations in python:

def inn(nums1,nums2):
    return set(nums1) & set(nums2)
  • Related