0

I was trying to do an assignment operation in python single line for loop like

[a[i]=b[i] for i in range(0,len(b))]

This seems wrong. Is there a way I can use assignment operation in python single line for loop?

MSeifert
  • 133,177
  • 32
  • 312
  • 322
syam
  • 367
  • 3
  • 17
  • 1
    Btw., what you are using is not a for loop but a list comprehension. – jotasi Jun 01 '17 at 09:18
  • Do `a` and `b` have the same length? And what is your use-case? Maybe there's an even better way (without loops or comprehensions). – MSeifert Jun 01 '17 at 09:42

5 Answers5

1

You are mixing two paradigms here, that of loop and list comprehension. The list comprehension will be

a = [x for x in b]
Elan
  • 443
  • 5
  • 14
1

Copy lists can be done in many ways in Python.

  • Using slicing

    a = b[:]

  • Using list()

    a = list(b)

Arun
  • 1,734
  • 1
  • 26
  • 40
1

No need for a loop. You can use a slice assignment:

a[0:len(b)]= b
Aran-Fey
  • 35,525
  • 9
  • 94
  • 135
1

You could use:

[a.__setitem__(i, b[i]) for i in range(0,len(b))]

the __setitem__ is the method that implements index-assignment. However doing a list comprehension only because of side-effects is a big no-no.

You could simply use slice-assignment:

a[:len(b)] = b
MSeifert
  • 133,177
  • 32
  • 312
  • 322
0

in python 3 it can be done by:

a = b.copy()
R.A.Munna
  • 1,609
  • 1
  • 13
  • 26