I am currently trying to build python code that removes the last element in a list in the case that any of three lists’s lengths do not equal to each other. This would save time going back into the lists and manually listExample{}.pop() to certain lists every time the criteria is not met.
The list with the lowest length should be the desired length of elements for all three lists. In this example, it would be four elements but ideally the program should count the lengths of the three lists and grab the lowest integer as it’s target. If the lists do not equal to each other, then the program will .pop() from the correct lists until listLength1 == listLength2 == listLength3 is met.
Here are the lists and variables I created to set up the example:
listExample1 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement', 'FifthElement', 'SixthElement']
listExample2 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
listExample3 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement', 'FifthElement']
listLength1 = len(listExample1)
listLength2 = len(listExample2)
listLength3 = len(listExample3)
print(listLength1) #6
print(listLength2) #4
print(listLength3) #5
Here is code I am currently building to attempt this:
if listLength1 == listLength2 == listLength3:
pass
elif listLength1 < listLength2:
pass
elif listLength1 > listLength3:
pass
elif listLength1 == listLength2:
pass
elif listLength2 < listLength1:
pass
elif listLength2 > listLength3:
pass
elif listLength2 == listLength1:
pass
elif listLength3 < listLength3:
pass
elif listLength3 > listLength1:
pass
elif listLength3 == listLength2:
pass
else:
pass
The if/elif seems redundant and I feel like there is room for error when I start listExample1.pop() in a certain condition which would likely mess up down the line. What is the best way to approach this?
Desired output:
print(listExample1) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
print(listExample2) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
print(listExample3) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
>Solution :
n = min(listLength1,listLength2,listLength3)
for i in range(listLength1-n):
listExample1.pop()
for i in range(listLength2-n):
listExample2.pop()
for i in range(listLength3-n):
listExample3.pop()
print(listExample1)
print(listExample2)
print(listExample3)
Output
['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']