-1

I want to declare a list in python3 and then update it with square values. e.g.

list1 = [1,2,3,4]

and Output should be the same list with square values:

list1 = [1,4,9,16]

I don't want to use another list. Please help?

Ashraf Mulla
  • 133
  • 2
  • 14
  • 5
    `list1 = [i * i for i in list1]`? – meowgoesthedog Jan 28 '19 at 13:40
  • 3
    Just use a boring old loop? – tobias_k Jan 28 '19 at 13:40
  • @meowgoesthedog That replaces the list, not the values in the list. – Bill the Lizard Jan 28 '19 at 13:42
  • @RahulAgarwal None of the answers in the "dupe" does it in-place. – tobias_k Jan 28 '19 at 13:42
  • You _could_ use a list comprehension and then do slice-assignment: `list[:] = [see comment above]`, but this will still create a new list temporarily. – tobias_k Jan 28 '19 at 13:43
  • @BilltheLizard OP should specify whether he meant a separate variable or a new list object. – meowgoesthedog Jan 28 '19 at 13:43
  • @tobias_k: The below posted answer is also the 2nd answer of the dupe!! – Rahul Agarwal Jan 28 '19 at 13:43
  • @RahulAgarwal Does not mean that the dupe is a dupe, just that the answer does not do what OP asks for. (Well, in fact, it does now) – tobias_k Jan 28 '19 at 13:44
  • This looked like a funny way to do this: https://stackoverflow.com/a/3000471/4121573 – Adonis Jan 28 '19 at 13:47
  • @tobias_k there is a target of modifying a list in place, that is considered a dup to a target that is not modifying a list in place... It seems like the other dup target was a poor choice of dup target, but this is an exact duplicate of the target that is pointing to a duplicate that is not an adequate target... – d_kennetz Jan 28 '19 at 15:50
  • See [this post](https://stackoverflow.com/questions/24201926/in-place-replacement-of-all-occurrences-of-an-element-in-a-list-in-python) as a duplicate target that is adequate. – d_kennetz Jan 28 '19 at 15:51

3 Answers3

4

You could use a slice-assignment with a generator expression:

>>> list1 = [1,2,3,4]
>>> list2 = list1
>>> list1[:] = (x**2 for x in list1)
>>> list2
[1, 4, 9, 16]

With the [:], it changes the list in-place, and by using a generator (...) instead of a list comprehension [...] it does not create a temporary list (in case that's the problem). (But note that if you have a reference to an element of that list, that reference will not be updated.)

tobias_k
  • 81,265
  • 12
  • 120
  • 179
2

You could use list1 = list(map(lambda x: x**2, list1)) but this doesn't work in place. It replaces the list. For doing it truly in place you loop over every item:

for i, x in enumerate(list1):
    list1[i] = x ** 2
0

Try this:

list1 = list(map(lambda x:x*x, list1))

or:

list1 = [i*i for i in list1]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59