Python - Find List A items in List B while keeping List A count

Hi, long time lurker, first time poster.
I’m starting off w/ Python and have a question.
I have a List A that contains View Names that are being imported from Excel. I then have the model’s Plan Views in List B and want to filter out the views that match List A. But I also want to keep the same number of element count as List A in the output. So if List A has 16 items, the result should show 16 items and “null” for any item not found in List B.
I know I can probably use Nodes for this, but I want to learn Python and so am looking for a Python only solution. I wrote something that works, but want to know if there’s a better way of doing things?? Thank!!!

As you are wanting the output list length to be the same as List A, iterating this list on the main loop (as you have done) is fine. Did you want the ‘null’ values to be Strings or actual Null values? In which case using results.append(None) would do the trick.

Nothing wrong with you solution :+1:

Another option would be to create an Array the same length as List A and populate it with Null values, only replacing items at indices where List B items occur. Then you can iterate over the Views which may be a shorter list.

2 Likes

@miguelvalencia5598 you can zip your inputs if you want, it will save you from creating the names list:

for e, viewName in zip(viewElementCollector, viewNamesExcel):
	if e.Name == viewName:
		results.append(e)
	else:
		results.append("null")
3 Likes

@Elie.Trad You need to watch you list structure for this, as it will default to lacing to the shortest list only, and if the value of e.Name doesn’t occur in the same index location as the viewName, then the ‘else’ will be thrown.

1 Like

If you want to use a zip method, you will need to use itertools to change the lacing :wink:

1 Like

Awesome, thank you all for your inputs, i really appreciate it and am going to go over it all. Will comeback if I run into any more issues.
Best,
Miguel

2 Likes

@Ewan_Opie great point! but I was showing how zip function can minimize code writing, as per the example provided (16 items IN, 16 items Out, and in order :wink: )

2 Likes