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?

2
  • 1
    Btw., what you are using is not a for loop but a list comprehension. Commented Jun 1, 2017 at 9: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). Commented Jun 1, 2017 at 9:42

5 Answers 5

1

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

a = [x for x in b]
Sign up to request clarification or add additional context in comments.

2 Comments

or why not a = b[:]
Does the same, but I think OP is trying to learn list comprehension as an alternative to looping over list. This explicitly conveys the idea.
1

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

a[0:len(b)]= b

Comments

1

Copy lists can be done in many ways in Python.

  • Using slicing

    a = b[:]

  • Using list()

    a = list(b)

1 Comment

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

Comments

0

in python 3 it can be done by:

a = b.copy()

Comments

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.