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?
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?
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.)
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
Try this:
list1 = list(map(lambda x:x*x, list1))
or:
list1 = [i*i for i in list1]