Shuffle a copy of a list [duplicate] - python

This question already has an answer here:
How to properly copy a list in python
(1 answer)
Closed 2 years ago.
It seems that the copy of a list is shuffled too?
So if I do for 2 lists:
data = examples
np.random.shuffle(examples)
then the list data is also shuffled? Why?

Python doesn't create copies of objects when it thinks they're not needed.
In your case you can use built-in copy module:
import copy
data = copy.deepcopy(examples)
np.random.shuffle(examples)

You have to do examples = np.copy(data) because otherwise the two variables will reference the same position in memory meaning they both change.

Related

How do I move values of one list to another list [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed last year.
I want to move the data from one list to another list to create a backup variable. I am currently using the code below but it seems to clear list1 for some reason too. If someone can explain the reasoning behind this and help me with a solution, I would be very grateful. I am new to python but I have some programming knowledge from Java.
list1 = list2
list2.clear()
The Python tutorial on W3Schools Copy Lists may help.
In Python you can copy list instances using my_list = my_other_list.copy(). This will create a copy of the list.
But why don't we just assign the list to a variable like my_list = my_other_list? That's because we would only point to the original list thus not creating a copy.
See also: List changes unexpectedly after assignment. Why is this and how can I prevent it?

Possible to convert string to a named variable or alternative? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
generating variable names on fly in python [duplicate]
(6 answers)
Closed 3 years ago.
I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.
The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.
Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?
list_1=['A','B']
list_2=['C','D']
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list):
for ticker in list:
if new_ticker in list:
return
else:
list.append(new_ticker)
list.remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
You key the needed lists by name in a dictionary:
ticker_directory = {
"list_1": list_1,
"list_2": list_2
}
Now you can accept the name and get the desired list as ticker_directory[assigned_list].
list_1=['A','B']
list_2=['C','D']
lists = {
'list_1':list_1,
'list_2':list_2
}
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list_name):
if old_ticker not in lists[list_name]:
return
else:
lists[list_name].append(new_ticker)
lists[list_name].remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
print(lists[assigned_list])
This is the complete program from what i perceived.
#prune already answered this, I have just given the whole solution
There are at least two possibilities:
1 As noted in comments kind of overkill but possible:
Use eval() to evaluate string as python expressions more in the link:
https://thepythonguru.com/python-builtin-functions/eval/
For example:
list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))
2 Second
Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.
list_name = 'list_1'
locals()[list_name].append(new_ticker)

How to avoid memory referencing to lists in python during continuous concatenation? [duplicate]

This question already has answers here:
python: changes to my copy variable affect the original variable [duplicate]
(4 answers)
Closed 4 years ago.
My requirement is , i want a final list as output which should
participate in loop during concatenation with other list (i got as an output of some other computation),but with below
implementation its not working due to memory referencing ,how can i avoid this. IN PYTHON
Please excuse me for my grammar
test_list=[[0,1],[2,3]]
result_list=[]
for i in range(3):
result_list=list(result_list)+list(test_list)
test_list.pop()
//this below line is affecting the result_list also,how to avoid this
test_list[0][1]+=1
Here is the time deepcopy comes in handy:
from copy import deepcopy
test_list=[[0,1],[2,3]]
result_list=[]
for i in range(3):
result_list+=deepcopy(test_list)
test_list.pop()
test_list[0][1]+=1
But as #RafaelC says it is giving error:
from copy import deepcopy
test_list=[[0,1],[2,3]]
result_list=[]
for i in range(1):
result_list+=deepcopy(test_list)
test_list.pop()
test_list[0][1]+=1
#RafaelC gave another good idea:
test_list=[[0,1],[2,3]]
result_list=[]
for i in range(1):
result_list=(result_list + test_list ).copy()
test_list.pop()
test_list[0][1]+=1

Value changes in new list impact previous list values, within a list of lists [duplicate]

This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 4 years ago.
I am looking to randomly generate a list and change one element in the list to create a new list. Whilst keeping track of all the generated lists.
For example:
values_possible = [0,0.5,1]
combinations = []
combinations.append([random.choice(values_possible) for i in range(8)])
lets say this generates
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
then if I copy this list and change one element, say combinations[1][1]
# set a new list to equal the first and then change one element
combinations.append(combinations[0])
combinations[1][1] = 0.33
print(combinations[0])
print(combinations[1])
this returns
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
it seems both combinations[0][1] and combinations[1][1] have changed to 0.33. Is there a way to solve this? May I ask why this happens and what I am misunderstanding about lists? I had expected the following output:
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
The short answer to your question is using colon:
combinations.append(combinations[0][:])
Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.
If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.
You can also take a look at this question and answer: python list by value not by reference
I hope this helps.
use
combinations.append(list(combinations[0]))
to append a copy of the first element.

Understanding slicing in python [duplicate]

This question already has answers here:
Slicing a list in Python without generating a copy
(5 answers)
Closed 5 months ago.
import numpy as np
x = np.arange(10**5)
for i in xrange(x.size):
foo(x[3000:40000])
and just another version of the code above
import numpy as np
x = np.arange(10**5)
slice_of_x = x[3000:40000]
for i in xrange(x.size):
foo(slice_of_x)
Will the second code be faster or not? I am inclined to think in terms of pointer in C (so that infact the first may be faster) but I understand python is no C.
O.k. This post
Slicing a list in Python without generating a copy
answers my question.
Read this http://scipy-lectures.github.io/advanced/advanced_numpy/#life-of-ndarray, in particular the section Slicing with integers.
From the page [on slicing]
Everything can be represented by changing only shape, strides, and possibly adjusting the data pointer!
Never makes copies of the data
So the overhead of creating a slice is small: constructing a Python object which stores a few tuples and a pointer to the data.
In your first code sample, you create the slice in the loop each time. In the second example you create the slice once. The difference will probably be negligible for most functions foo that you would choose to write.

Categories