Python Forum
Help: list comprehension for loop with double if statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help: list comprehension for loop with double if statement
#1
Hi,

I have the following piece if code which I want to write more cleanly using list comprehension.
However, I am struggling with the list comprehension using the double if statement in the for loop.
Can somebody help me with this?

data = {'caseA': ['Printers'], 'caseB': None, 'caseC': ['Printers', 'Computers'], 'caseD': None, 'caseE': None}
item = 'Printers'

relations = ''

if data:
    for case in data:
        if data[case] is not None:
            if item in data[case]:
                label = 'affected'
            else:
                label = 'unaffected'
        else:
            label = 'unaffected'

        relations = relations + label + ','
I have this:
if data:
   label = ['unaffected' if data[case] is None else 'affected' for case in data if item in data[case]]
but it results in an error related to 'None':
Error:
label = ['unaffected' if data[case] is None else 'affected' for case in data if current_element in data[case]] TypeError: argument of type 'NoneType' is not iterable
Thanks!
Reply


Messages In This Thread
Help: list comprehension for loop with double if statement - by mart79 - May-04-2020, 06:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 438 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 426 Oct-17-2023, 09:46 AM
Last Post: tomciodev
Photo Python code: While loop with if statement HAMOUDA 1 535 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  Using list comprehension with 'yield' in function tester_V 5 1,175 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Multiply and Addition in the same loop statement with logic. joelraj 2 998 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  list comprehension 3lnyn0 4 1,359 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,601 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  List comprehension used differently coder_sw99 3 1,679 Oct-03-2021, 04:12 PM
Last Post: coder_sw99
  Change a list to integer so I can use IF statement buckssg 3 2,194 Sep-21-2021, 02:58 AM
Last Post: bowlofred
  How to invoke a function with return statement in list comprehension? maiya 4 2,746 Jul-17-2021, 04:30 PM
Last Post: maiya

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020