zello360
zello360

Reputation: 3

how can I make the original list passed though the function and modified, but don't return a new list instead add on to old list?

list outputs 4, 16, 36 but should be outputting 2, 4, 6, 4, 16, 36 a combined list of my original numbers and new numbers if i take the old ones and **2.

def squareEach(nums):
    
    for i in range(len(nums)):
        
        nums [i] = nums[i]**2

def test ():
    
    nums = [2,4,6]
    
    squareEach(nums)
    
    print("List:", nums)

test()   

Upvotes: 0

Views: 42

Answers (2)

Samwise
Samwise

Reputation: 71454

You need to append to, or extend, the list.

>>> def append_squares(nums):
...     nums.extend([n ** 2 for n in nums])
...
>>> nums = [2, 4, 6]
>>> append_squares(nums)
>>> nums
[2, 4, 6, 4, 16, 36]

Upvotes: 1

csjh
csjh

Reputation: 192

Instead of nums[i] = nums[i]**2, do nums.append(nums[i]**2)

Upvotes: 1

Related Questions