Gabe
Gabe

Reputation: 13

making a new modified version of a list without modifying the original list in python

i need to modify the contents of my og list into a different list w/out actually changing my og list.

def createList(numbers):
  my_List= [0] * numbers 
  for q in range(0, len(my_List)):
      myList[q]= randint (1, 21)
      q=q+1
  return my_List

def modifyList(newList):
  for i in range(0, len(newList)):
    if i % 2 == 0:
      newList[i]= newList[i] / 2
    else:
      newList[i]= newList[i] * 2
  return newList

def main():
  my_List= createList(10)
  print my_List
  newList= modifyList(my_List)
  print my_List
  print newList

Upvotes: 1

Views: 68

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

Here's an alternate way, with list comprehensions. In Python, you usually don't have to create a list with placeholders and put the elements one by one:

>>> from random import randint
>>> my_list = [randint(1, 20) for _ in range(10)]
>>> my_list
[1, 20, 2, 4, 8, 12, 16, 7, 4, 14]
>>> [x * 2 if i % 2 else x / 2 for i, x in enumerate(my_list)]
[0.5, 40, 1.0, 8, 4.0, 24, 8.0, 14, 2.0, 28]

If you want to modify the original list in place, you could use numpy and advanced slicing:

>>> import numpy as np
>>> a = np.array([11, 13, 21, 12, 18, 2, 21, 1, 5, 9])
>>> a[::2] = a[::2] / 2
>>> a[1::2] = a[1::2] * 2
>>> a
array([ 5, 26, 10, 24,  9,  4, 10,  2,  2, 18])

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20414

You need to make a copy of the list that is inputted to the modifyList function. This copy isn't done with myList[:] as you are not working with myList here! You are working with a different variable called newList which you need to make a copy of.

You need to remember that a function works with a variable that is passed into it but under the name it has been assigned in the function definition. So here, even though you only call the function with modifyList(myList), inside the function, you are always working with newList so trying to do anything with myList here will throw an error saying its undefined.

def modifyList(newList):
  newList = newList[:]
  for j in range(0, len(newList)):
    if j % 2 == 0:
      newList[j]= newList[j] / 2
    else:
      newList[j]= newList[j] * 2
  return newList

Upvotes: 2

Related Questions