-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
  • 123
  • 1
  • 12

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
  • 78,071
  • 11
  • 109
  • 168
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
  • 9,989
  • 4
  • 33
  • 55