1

I have a list (aList) I need to create another list of the same length as aList (checkColumn) and add 1 at the positions defined in the index list (indexList), the positions not defined in the indexList should be 0

Input:

aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]

Desired Output:

checkColumn = [1,1,0,0,0,1]

I have been experimenting around with the following code, but I get the output as [1,1]

for a in len(aList):
    if a == indexList[a]:
        checkColumn = checkColumn[:a] + [1] + checkColumn[a:]
    else:
        checkColumn = checkColumn[:a] + [0] + checkColumn[a:]

I have tried with checkColumn.insert(a, 1) and I get the same result. Thanks for the help!

3
  • 1
    Can I ask why do you need this exactly? Can you describe the problem that led to this solution? Commented Sep 3, 2018 at 15:45
  • aList is the id of all items, of these I have already identified the indexes of the bad items and put it in indexList. Now I want to mark in another list (check) the items that are bad (1) and those good (0) Commented Sep 3, 2018 at 16:30
  • This re-describes the problem you've presented. Not how it spawned. I think there may be a simpler solution to what you're doing on a higher-level. Good luck :) Commented Sep 3, 2018 at 16:35

2 Answers 2

3

Would this help?

First, you initialize checkColumn with 0

checkColumn = [0] * len(aList)

Then, loop through indexList and update the checkColumn

for idx in indexList:
    checkColumn[idx] = 1

Cheers!

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

Comments

2

You could do this in one line using a list comprehension:

aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]

checkColumn = [1 if a in indexList else 0 for a in range(len(aList))]
print(checkColumn)
# [1, 1, 0, 0, 0, 1, 0, 0]

1 Comment

You can make in even shorter with int(a in indexList)

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.