Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If-Elif Statement is not working as I expected in python

I want to adjust lists to the same length but the if-elif statement is not working as I thought, its very weird. This might be something so obvious

Code:


l = [1,2,1,4,3,1]
l2 = [1,5,7,3,35,5,66,7]
lenl = len(l)
lenl2 = len(l2)
if l < l2:
    l_l2 = lenl - lenl2
    list1 = l2
    list2 = l
elif l > l2:
    l_l2 = lenl2 - lenl
    list1 = l
    list2 = l2
for i in range(0,l_l2):
    list1.append(None)
print(list2)
print(list1)
for i in range(0,l_l2):
    list1.remove(None)
print(list1)

I keep getting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


[1, 2, 1, 4, 3, 1]
[1, 5, 7, 3, 35, 5, 66, 7]
[1, 5, 7, 3, 35, 5, 66, 7]

What I want:


[1, 2, 1, 4, 3, 1,None,None]
[1, 5, 7, 3, 35, 5, 66, 7]
[1, 5, 7, 3, 35, 5, 66, 7]

>Solution :

Your main issue is comparing two lists instead of using the length of each. Also, I feel like you swapping the lists might’ve confused you and propagated down to the rest of the code (lines 8 & 9 and 13 & 14 -> affected lines 16 & 20). Nevertheless, I just fixed some parts and think it should work now for what you want it to do. Also, you might want to double-check your math for getting the length.

l = [1,2,1,4,3,1]
l2 = [1,5,7,3,35,5,66,7]
lenl = len(l)
lenl2 = len(l2)
if lenl < lenl2:
    l_l2 = abs(lenl - lenl2)
    list1 = l2
    list2 = l
elif lenl > lenl2:
    l_l2 = abs(lenl2 - lenl)
    list1 = l
    list2 = l2
for i in range(0,l_l2):
    list2.append(None)
print(list2)
print(list1)
for i in range(0,l_l2):
    list2.remove(None)
print(list1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading