[SOLVED] 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?

Issue

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()   

Solution

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]

Answered By – Samwise

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.