Home > Software engineering >  Check if an element is present in multiple lists in python and append it
Check if an element is present in multiple lists in python and append it

Time:11-08

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:

# 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

CodePudding user response:

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"]
  • Related