Variable name as function argument? [duplicate] - python

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 6 years ago.
I wish to make a function whose arguments are the name of a list L, and its arguments. The list L has just numbers in it, and I want to round them all to 1 decimal(by the way, the elements of the list L should be replaced by the rounded numbers, I don't want a new list M with them). Sadly, the list name varies in the script I'm planning, and so does the length of such lists. Here is my failed attempt:
def rounding(name,*args):
M=[round(i,1) for i in args] #here is the list I want L to become
name=M #here I try to replace the previous list with the new one
morada=[1,2.2342,4.32423,6.1231] #an easy example
rounding(morada,*morada)
print morada
Output:
[1, 2.2342, 4.32423, 6.1231] #No changes

Have the rounding function return a value.
def rounding(list_):
return [round(i, 1) for i in list_]
Then you can do this:
>>> morada=[1,2.2342,4.32423,6.1231] #an easy example
>>> morada = rounding(morada)
>>> morada
[1, 2.2, 4.3, 6.1]
Or if you really really wanted it to assign within the function you could do this:
def rounding(list_):
list_[:] = [round(i,1) for i in args]

Close. Lists are mutable, so...
name[:] = M

You can use eval()
For example, the following will start with a list containing [1, 2, 3, 4] and change the first element to 5:
list_0 = [1, 2, 3, 4]
def modify_list(arg):
list_1 = eval(arg)
list_1[0] = 5
modify_list('list_0')
print list_0

Related

Why hasn't this list changed? [duplicate]

This question already has answers here:
Python functions call by reference [duplicate]
(12 answers)
Closed 3 years ago.
In the following code, the function modify_list want to modify b, but it failed, the print result is [1,2,3]. why hasn't the list a changed?
def modify_list(b):
b = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
If you want something like this to work you can do:
def modify_list(b):
return [1,2]
a = [1,2,3]
a = modify_list(a)
print(a)
Or
def modify_list(b):
b[:] = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
you are declaring other local variable b, if you want to mutate you can do:
b[:] = [1, 2]
or even better you can return your desired value for list a
if you want to change your list a value you can assign the desired value:
a = [1, 2]

Reverse list in array Python using append remove method without build in function [duplicate]

This question already has answers here:
Modifying a list while iterating when programming with python [duplicate]
(5 answers)
Closed 4 years ago.
I am trying to reverse a list using append and remove method. But there is a problem in my method of doing this solution. Perhaps anyone give me a better explanation
list_in_order = [1,2,3,4,5,6]
def reverse(list):
r=[]
for i in list:
print (i)
r.append(i)
list_in_order.remove(i)
return r
print(reverse(list_in_order))
You can't use list.append, as that appends to the end of the list. What you want is to append to the start of the list. For that use list.insert. For more details see the list docs.
list_in_order = [1,2,3,4,5,6]
def reverse(L):
r = []
for i in L:
r.insert(0, i)
return r
print(reverse(list_in_order))
The other option is of course to use slice notation.
>>> [1,2,3,4,5,6][::-1]
[6, 5, 4, 3, 2, 1]
To make some constructive criticisms of the code in your question
Don't refer to variables outside of the function, unless you really intend to use globals. list_in_order.remove(i) refers to your global variable, not your function argument (although they ultimately refer to the same thing in this case). It may have been a typo but its worth pointing out that it's not quite right.
Don't use variable names that hide built in types. list, dict, tuple, set etc... These are not good names for variables as they will hide those types from further use in the scope that variable exists in and it may be difficult to find the source of the errors you get as a result.
Make your functions do one of two things; either modify the input (called in place modification) and return None or create a new collection and return that.
Don't iterate over a collection while modifying it. See linked dupe for elaboration.
In [11]: list_in_order = [1,2,3,4,5,6]
In [12]: list(reversed(list_in_order))
Out[12]: [6, 5, 4, 3, 2, 1]
Do you want [6, 5, 4, 3, 2, 1] for the result?
If so, just use list_in_order[::-1]
If you must use the append and remove,
list_in_order = [1,2,3,4,5,6]
def reverse_list(target_list):
copied_list = target_list.copy()
r=[]
for i in reversed(target_list):
r.append(i)
copied_list.remove(i)
return r
don't remove list elements when it in loop.
don't use 'list' for variable/parameter name.
I would make it like this :
list_in_order = [1,2,3,4,5,6]
def reverse(list):
counter = len(list)
for i in range(0,counter/2):
print(i)
list[i],list[counter-i] = list[counter-i], list[i]
return list
print(reverse(list_in_order))
This is a one way to do it, but you can do it using a recursion :)

Python : Why is single step conversion of a tuple to list and appending to it not working? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 5 years ago.
aTup = (1,2,3)
print(list(aTup).append(4))
Why does it display None?
append returns None, simple as that. It does however modify the list
>>> l = [1,2,3]
>>> print(l.append(4))
None
>>> l
[1, 2, 3, 4]
The reason is that it isn't meant to be called with the return value used mistakenly for an assignment.
l = l.append(4) # this is wrong
It's because the method append() does not return any value.
If you want to print the list after the update, you can do the following:
aTup = (1,2,3)
aList = list(aTup)
aList.append(4)
print(aList)

Copy a list of list by value and not reference [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Copying nested lists in Python
(3 answers)
Closed 4 years ago.
To understand why I was getting an error in a program , in which I tried to find the "minor" of a determinant, I wrote a simpler program because my variables were messed up. This function below takes in a 2 * 2 matrix as an input, and returns a list containing its rows (pointless and inefficient, I know, but I'm trying to understand the theory behind this).
def alpha(A): #where A will be a 2 * 2 matrix
B = A #the only purpose of B is to store the initial value of A, to retrieve it later
mylist = []
for i in range(2):
for j in range(2):
del A[i][j]
array.append(A)
A = B
return mylist
However, here it seems that B is assigned the value of A dynamically, in the sense that I'm not able to store the initial value of A in B to use it later. Why is that?
Because python passes lists by reference
This means that when you write "b=a" you're saying that a and b are the same object, and that when you change b you change also a, and viceversa
A way to copy a list by value:
new_list = old_list[:]
If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
import copy
new_list = copy.deepcopy(old_list)
Since Python passes list by reference, A and B are the same objects. When you modify B you are also modifying A. This behavior can be demonstrated in a simple example:
>>> A = [1, 2, 3]
>>> def change(l):
... b = l
... b.append(4)
...
>>> A
[1, 2, 3]
>>> change(A)
>>> A
[1, 2, 3, 4]
>>>
If you need a copy of A use slice notation:
B = A[:]
A looks like a reference type, not a value type. Reference types are not copied on assignment (unlike e.g. R). You can use copy.copy to make a deep copy of an element

list.append() in python returning null [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 6 years ago.
What is the actual difference between list1.append() and list1+list2 in python??
Along with this, why the following statement return NULL?
print(list1.append(list2))
{where list1 and list2 are 2 simple list}
list.append() modifies the object and returns None.
[] + [] creates and "returns" new list.
https://docs.python.org/2.7/tutorial/datastructures.html#more-on-lists
Recommended reading: http://docs.python-guide.org/en/latest/writing/gotchas/
Returning None is a way to communicate that an operation is side-effecting -- that is, that it's changing one of its operands, as opposed to leaving them unchanged and returning a new value.
list1.append(list2)
...changes list1, making it a member of this category.
Compare the following two chunks of code:
# in this case, it's obvious that list1 was changed
list1.append(list2)
print list1
...and:
# in this case, you as a reader don't know if list1 was changed,
# unless you already know the semantics of list.append.
print list1.append(list2)
Forbidding the latter (by making it useless) thus enhances the readability of the language.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.append(b) # append just appends the variable to the next index and returns None
>>> print a
[1,2,3,[4,5,6]]
>>> a.extend(b) # Extend takes a list as input and extends the main list
[1,2,3,4,5,6]
>>> a+b # + is exactly same as extend
[1,2,3,4,5,6]
When you print a function, you print what it returns and the append method does not return anything. However your list now has a new element. You can print the list to see the changes made.
list1 + list2 means that you combine 2 lists into one big list.
list1.append(element) adds one element to the end of the list.
Here's an example of append vs +
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>>
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]

Categories