Home > Back-end >  how can I make the original list passed though the function and modified, but don't return a ne
how can I make the original list passed though the function and modified, but don't return a ne

Time:01-23

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

CodePudding user response:

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

CodePudding user response:

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]
  •  Tags:  
  • Related