This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 3 years ago.
I've got this function that removes the second data value from a list (simplified). However when executing the function, the original list seems to get modified even though I'm only doing something to the variable inside the function.
print(data_values)
def remove_2(data):
data.pop(2)
return data
new_data = remove_2(data_values)
print(data_values)
>>>['a', 'b', 'c', 'd']
>>> ['a', 'b', 'd']
I'm printing out the original data_values both times, but the second time it's the modified version even though only the variable inside the function was modified.
The pop() function removes the element with the given index what you're doing is removing the element with index 2 from the original list and then using another list to display it
print(data_values)
def remove_2(data):
data.pop(2)
return data
new_data=data_values[:]
new_data = remove_2(new_data)
print(data_values)
print(new_data)
You should use another list if you don't want the default list to be changed
Related
This question already has answers here:
Insert an element at a specific index in a list and return the updated list
(6 answers)
Closed 1 year ago.
all I am learning python from some days back, and please help me to How to Write a Python program to insert a new item before the second element in an existing array
The python list data structure has a insert method associated with it..
The insert method takes two arguments position, value-to-insert.
So for your case it will be something like this.
In [1]: l1 = ['a','b','c','d']
In [2]: l1.insert(1,'x')
In [3]: l1
Out[3]: ['a', 'x', 'b', 'c', 'd']
In [4]:
We are inserting at index 1, because list index starts with 0.
This question already has answers here:
How can you print a variable name in python? [duplicate]
(8 answers)
Closed 2 years ago.
What?
I want to use a variable's name, not it's value. For instance, in the following example, I would like the function to return my_list[1] , and not B..
my_list = ['A', 'B']
def example(list_element):
print(repr(eval(list_element)))
example(my_list[1]) # I would like this to print `my_list[1]`
But Why?
I am trying to create a function that takes a given element from a list, and also uses the previous list element. By getting the name my_list[1], I can subtract one and also get my_list[0]. Once I have both the names, I can utilise the values stored under these names.
Yes, I could simply add two fields to the function and put them in each time but I was hoping to keep the body of my code a little easier to read.
Don't use data to manipulate your code, it's not how Python (or most languages) works.
To do what you're trying to do:
my_list = ['A', 'B']
def example(a_list, index):
print('The element passed: ', a_list[index])
print('The element before it: ', a_list[index-1])
example(my_list, 1)
Of course this doesn't check if you didn't accidentally pass 0, etc. - but it shows you don't need to make a mess with eval, exec, etc.
This question already has answers here:
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
Closed 5 years ago.
I'm looking to assign items to variables using a loop, where the names of the variables are already predetermined from a list. I've got a list set up, and I'm having issues within the loop. My code is similar to this:
dict_Name = { 'a', 'b', 'c', ... , 'k', 'l'}
for input_x in list_Name:
dict_Name['self.var_'+input_x] = round(float(eval('self.ui.inp_'+input_x).text()), 2)
print ('self.var'+input_x)
Where the dictionary goes from 'a' to 'l'. Here, the rounded floating number is coming from user input (GUI created with PyQt) where the input value name is "inp_a", for example. I'm looking to assign the "inp_a" value to "var_a", but I'm having trouble with this.
The current error is that the " 'set' object does not support item assignment". I'm assuming this means I can't use the dictionary tool to assign variables from the user input, but I'm not sure about that.
Any help is much appreciated.
In your first line you've created a set:
dict_Name = { 'a', 'b', 'c', ... , 'k', 'l'} # not a dict
dict is a mapping of items into other items, where do you see any mapping here?
For example this is a dict:
real_dict = {'a' : 'val_a', 'b' : 'val_b'}
set on the other hand is a collection of unique objects, and that's what you've created on the first line.
This question already has answers here:
Modifying a list while iterating over it - why not? [duplicate]
(4 answers)
Closed 6 years ago.
I've found a python puzzle and can't find out why it works.
x = ['a','b','c']
for m in x:
x.remove(m)
and after this loop x = ['b'].
But why?
As far as I understand for keyword implicitly creates iterator for this list. Does .remove() calls __next__() method so b is skipped? I can't find any mentions of it but this is my best guess.
Here you are iterating over the original list. On the first iteration, you removed the 0th index element i.e. a. Now, your list is as: ['b','c']. On the second iteration your for loop will access the value at index 1 but your index 1 has value c. So the c is removed. Hence resultant list will be ['b'].
In order to make it behave expectedly, iterate over the copy of the list, and remove the item from original list. For example:
x = ['a','b','c']
for m in list(x): # <-- Here 'list(x)' will create the copy of list 'x'
# for will iterate over the copy
x.remove(m)
# updated value of 'x' will be: []
Note: If it is not for demo purpose and you are using this code for emptying the list, efficient way of emptying the list will be:
del x[:]
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 9 years ago.
I am trying to get an element from list and make some change on this element (which is also a list). Weirdly, the change applied on the previous list. Here is my code:
>>>sentences[0]
['<s>/<s>',
'I/PRP',
'need/VBP',
'to/TO',
'have/VB',
'dinner/NN',
'served/VBN',
'</s>/</s>']
>>>sentence = sentences[0]
>>>sentence.insert(0,startc); sentence.append(endc)
>>>sentences[0]
['<s>/<s>',
'<s>/<s>',
'I/PRP',
'need/VBP',
'to/TO',
'have/VB',
'dinner/NN',
'served/VBN',
'</s>/</s>'
'</s>/</s>']
It is like I just got a pointer to that element, not a copy
You do get a "pointer", in fact. Lists (and any mutable value type!) are passed around as reference in Python.
You can make a copy of a list by passing it to the list() object constructor, or by making a full slice using [:].
a = [1,2,3]
b = a
c = list(a)
d = a[:]
a[1] = 4 # changes the list referenced by both 'a' and 'b', but not 'c' or 'd'
You're exactly right! In Python, when you pass a list as an argument to a function, or you assign a list to another variable, you're actually passing a pointer to it.
This is for efficiency reasons; if you made a separate copy of a 1000-item list every time you did one of the aforementioned things, the program would consume way too much memory and time.
To overcome this in Python, you can duplicate a one-dimensional list using = originalList[:] or = list(originalList):
sentence = sentences[0][:] # or sentence = list(sentences[0])
sentence.insert(0,startc)
sentence.append(endc)
print(sentence) # modified
print(sentences[0]) # not modified
Consider using list comprehension if you need to duplicate a 2D list.