'Genereating new list inside local scope and assigning it to a variable in global scope
Good day, guys. Is it possible to modify list inside function definition and assign new list to variable in global scope. For example, I dont like figure 6:
list = [1,2,3,4,5,6,7,8,9]
def modification(data):
new_sexy_list = []
for index in data:
if index == 6:
del index
return **???????????????**
output
modification(list)
list = [1,2,3,4,5,7,8,9]
How could return statement look like?
Solution 1:[1]
You can just mutate the list inside the function:
li = [1,2,3,4,5,6,7,8,9]
def modification(data):
data.pop(6) # remove element at index 6
modification(li)
print(li) # will print [1, 2, 3, 4, 5, 6, 8, 9]
Note that there's no need to return anything.
Another possibility is to build a new list inside the function and return it.
If you don't understand how this works, I highly recommend reading https://nedbatchelder.com/text/names.html. Python names (references) and values work differently from many other languages. The article explains it very well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
