0

I have the following loop in Python that I want to turn into a list comprehension:

index = 0
    for i in range(number):
        vec[i] = index
        if condition:
            index += 1

This should make vec look something like [0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 6, 6]. However, I am struggling to create a list comprehension for this.

My attempts look like this:

y=[]
index = 0
[index+=1 and y.append(index) if condition else y.append(index) for _ in range(number)]

In iPython this just doesn't even execute.

1
  • 1
    You shouldnt use list comprehensions for side effects to begin with they are for expressing declarative mapping/filtering operations Commented Jul 8, 2020 at 23:48

1 Answer 1

3

The walrus operator can do the job for you ... but I heartily agree with @juanpa: don't. This is hard to read and hard to debug.

>>> index = 0
>>> [ index := (index+1 if i%3 == 1 else index) for i in range(10) ]
[0, 1, 1, 1, 2, 2, 2, 3, 3, 3]

I've used i%3 == 1 as your "condition".

Sign up to request clarification or add additional context in comments.

2 Comments

Fascinating, I've never heard of the walrus operator. I'll have to check it out. Are there uses for it which are not difficult to read or debug?
Remember the first rule of posting: research, research, research. Don't ask me whether there are such uses -- look it up! Yes, there are. The operator is new in Python 3.8, I think, and it has much better uses. The name comes from turning the operator sideways, like a :-) smiley.

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.