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?

DominicR
  • 125
  • 5

4 Answers4

2

Iterate through the indices and update the list manually:

a = [0] * 10
for index in indices:
  a[index] = 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98
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]
CanciuCostin
  • 1,773
  • 1
  • 10
  • 25
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)
JTateCC
  • 56
  • 4
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]
dimay
  • 2,768
  • 1
  • 13
  • 22