Virgilio
Virgilio

Reputation: 41

Changing List elements in a For loop

This script works for what I need it to, but while researching how to make this I found many comments that it is the wrong way to do this. The comments that I found are not very descriptive, and don't really seem to apply to my use case. I can't put my finger on if or why this is wrong, what can I do to improve this?

myList1 = [1, 2, 3, 4, 5]
myList2 = [1, 3, 5]
myList3 = []

for i in myList1:
    myList3.append(0)
for j in range(len(myList1)):
    for k in range(len(myList2)):
        if myList1[j] == myList2[k]:
            myList3[j] = 1

print(myList3)

My output is what I want:

[1, 0, 1, 0, 1]

So I want to make myList3 to be the same length as myList1, and populate it with zeros.

I want to then compare myList1 with myList2 and if there are matches, then that element number of myList1 receives some value.

Maybe there is nothing wrong with this and the reason I can't find an answer is that it's just fine?

Upvotes: 0

Views: 49

Answers (3)

bipll
bipll

Reputation: 11950

Your code works in O(len(myList1) * len(myList2)) time which might constitute a problem when lists are large enough (and coincidental elements are evenly spread in myList2). One simple optimization would be to turn myList2 into a set in advance:

mySet2 = frozenset(myList2)
myList3 = [1 if element in mySet2 else 0 for element in myList1]

This code would have a notably better O(len(myList1) + len(myList2)) average running time.

Upvotes: 1

Hugh Craig
Hugh Craig

Reputation: 129

I mean technically there is nothing wrong with this at all. It is just a little bit strange that you are using for i in myList1:, as you don't really use i for anything. I liked @MisterMiyagi's answer in terms of how succinct it is, but if you are just looking for a simple way to intialize myList3 you could have just done myList3 = [0]*len(myList1).

Upvotes: 0

MisterMiyagi
MisterMiyagi

Reputation: 52149

There is nothing inherently wrong with your approach. However, there is no need for so much explicit looping and testing:

myList1 = [1, 2, 3, 4, 5]
myList2 = [1, 3, 5]
myList3 = [1 if element in myList2 else 0 for element in myList1]

This basically merges the two loops walking myList1 (once for 0 and once for comparison), and removes the loop to search myList2 for matches. Using such a style is usually preferable, as it is largely about what you want, not how to get there.

Note that depending on how much data you have, you want myList2 to be a set. A set has constant time for lookups, whereas a list is fast for few elements but slows down with more elements.

myList1 = [1, 2, 3, 4, 5]
mySet2 = {1, 3, 5}
myList3 = [1 if element in mySet2 else 0 for element in myList1]

Upvotes: 1

Related Questions