1

What is a Pythonic way to use a list as an index in Python? With numpy you can do the following:

import numpy
a = numpy.zeros(10)
indices = [1,3,6]
a[indices] = 1
# This gives [0,1,0,1,0,0,1,0,0,0]

What is the simplest way to replicate this without using numpy?

2
  • Someone is spamming answers with downvotes - upvote the answers you like and their influence will be insignificant. Commented May 23, 2020 at 12:04
  • I thought so too Commented May 23, 2020 at 12:05

4 Answers 4

2

Iterate through the indices and update the list manually:

a = [0] * 10
for index in indices:
  a[index] = 1
Sign up to request clarification or add additional context in comments.

Comments

1

You could create an array of zeros on your own:

a=[0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

indices = [1,3,6]
for index in indices:
    a[index]=1

>>> a
[0, 1, 0, 1, 0, 0, 1, 0, 0, 0]

Comments

0

maybe just use a loop and conditionally append to a list

a = []
indices = [1,3,6]
for i in range(10):
    if i in indices:
        a.append(1)
    else:
        a.append(0)

Comments

0

You can do it with list comprehension

indices = [1,3,6]
a = [1 if i in indices else 0 for i in range(10) ]
# [0, 1, 0, 1, 0, 0, 1, 0, 0, 0]

1 Comment

This is what I as going to suggest - a nice clean one-liner.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.