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
  • 145,886
  • 38
  • 333
  • 352
syam
  • 387
  • 4
  • 19
  • 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,933
  • 2
  • 28
  • 46
1

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

a[0:len(b)]= b
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
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
  • 145,886
  • 38
  • 333
  • 352
0

in python 3 it can be done by:

a = b.copy()
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29