0

I've got the code as follows:

ix=0
list_test=[]
for el in parse_data_2['var_nm_final']:    
    if el=='URI':
        ix+=1
        list_test.append(ix)
    else:
        list_test.append(None)

parse_data_2 is my DF. As an output I would like to receive list with incremented value of ix or None depending on my condition. Meaning something like this

1
None
None
None
None
2
None
3
None
None
None
None
4

... etc.

I've tried to convert this loop to list comprehesion like this:

[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]         

but got error

[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]
       ^
SyntaxError: invalid syntax

Could you explain me the issue with my code?

1
  • Personally I would use the explicit loop in this case. It's clear what it does, it's extremely easy to read, and it does what you want. Commented Nov 9, 2021 at 15:59

2 Answers 2

4

Use next on an itertools.count (or just range with generous upper bound):

>>> parse_data_2 = {'var_nm_final': ["URI", "foo", "bar", "URI", "URI", "blub", "URI"]}
>>> import itertools
>>> cnt = itertools.count(1)
>>> [next(cnt) if el == "URI" else None for el in parse_data_2["var_nm_final"]]
[1, None, None, 2, 3, None, 4]
Sign up to request clarification or add additional context in comments.

1 Comment

Awsome, didn't know it. thx
1

This is a great use-case for the walrus operator! But please, don't do this. Whatever you're trying to accomplish, this can almost certainly be done in a pythonic and performant manner.

[(ix:=ix+1) if el=='URI'else None for el in parse_data_2['var_nm_final']]   

5 Comments

well.. it's a usecase, I grant that ;)
Please never write code like this...
@MarcoBonelli I hear you, this is terrible code. That said, it does what OP asked for...
What are disadvantages of this code?
@data_b77 whatever you're trying to do with your el variable can likely be accomplished by something like parse_data_2['var_nm_final'].eq('URI').sum() or similar -- generating a list comprehension with side-effects on your element generator is poor form, and likely not the most performant solution either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.