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

Check if an element is present in multiple lists in python and append it

I have a different columns in excel csv file, and I want to check for a condition in different columns and when condition is met, to append the found value to my new list.

But it’s not working.

This is my code:

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

# importing module
from pandas import *

# reading CSV file
data = read_csv("test.csv")

# converting column data to list
ext1 = data['ext1'].tolist()
int1 = data['int1'].tolist()
ext2 = data['ext2'].tolist()

ext = []


for i in ext1 or ext2:
    if i >= "2022-03-01":
        ext.append(i)
    else:
        pass

print(*ext, sep="\n")

The problem is there:

for i in ext1 or ext2:

I think the or is problematic.

This is my csv file:

ext1,int1,ext2
2023-01-20,2022-01-20,2022-01-21
2024-01-21,2023-01-22,2024-12-22
2021-01-22,2022-01-22,2022-01-23

The list should print:

2023-01-20
2024-01-21
2024-12-22

it’s only printing:

2023-01-20
2024-01-21

>Solution :

I can’t say I fully understood the issue but try

for i in ext1 + ext2:

ext1 or ext2 simply means "use ext1 if not empty, otherwise ext2".

Also get rid of else: pass as it is redundant.

As a side note, your whole loop can be rewritten in a single line as a list comprehension:

ext = [i for i in ext1 + ext2 if i >= "2022-03-01"]
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