Upon shuffling I get a None object. What is wrong? - python

I have shuffled the list and assigned it to another variable and when I am trying to print it, it is giving output as None? What is wrong ?
list1 = [1,2,3,4,5,6]
list2 = shuffle(list1)
print list2

The random.shuffle() function is designed to take a list and shuffle its contents. It does not return the shuffled list. The documentation states:
Shuffle the sequence x in place.
As such, if you try to assign the return to a variable you will get None.
You can do the following instead:
list1 = [1,2,3,4,5,6]
shuffle(list1)
print list1
If you wish to preserve your original list order:
list1 = [1,2,3,4,5,6]
list2 = list1[::] # make a copy
shuffle(list2)
print list2

Shuffle() function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object.
#!/usr/bin/python
import random`
list = [1, 2, 3, 4, 5];
random.shuffle(list)
print "list : ", list

Related

Python list - call function with different values

def check(val, list=[]):
list.append(val)
return list
list1=check("a")
list2=check("b",[])
list3=check("c")
If I run list1 and check the output it shows ["a"]
But, If I run list1, list2 and list3 in one
cell and check for list1 it shows ['a','c'], can someone please explain why is it so?
This is the right way to do this:
def check(val, values=None):
if values is None:
values = []
values.append(val)
return values
list1 = check("a")
list2 = check("b", [])
list3 = check("c")
Default argument values should not be mutable. You can find a good explanation here,
And list is a poor name for a variable, because list is a built-in type, as are str, set, dict.
It seems that list1 and list3 share same object.
You can try this:
def check(val, list=[]):
list.append(val)
print(hex(id(list)))
return list
list1=check("a")
list2=check("b")
list3=check("c")
print(list1)
print(list2)
print(list3)

List non-mutating method

Is there in python any method that instead of mutate the original list it returns a new object?
In JavaScript there is at least one:
const originalArray = [1,2,3]
originalArray.concat(4) // returns a new array
In Python, this will return a new list:
originalArray = [1,2,3]
originalArray + [4]
Or if you want to create a new copy of the list use slices:
originalArray[:]
List comprehensions will also create a new list:
[x for x in originalArray]
This is yet another way:
import copy
copy.copy(originalArray)
And there's also the built-in copy() method, as shown in Ronald's answer.
You can simply use the copy method:
list1 = ['a','b','c']
list2 = list1.copy()
list1 is list2, list1 == list2
returns
(False, True)
Showing that you have new object with the same content.

Python Theory About Equal Operator and Array Definition

I stumbled upon a theoretical question about how python works, and it got me puzzled. I tried to understand exactly what happened but couldn't find the answer in google - I'm a beginner, so I don't even know the terminology to make the apropriate search.
On the following code, when calling the function it changes myList, while I only wanted to create a list2 which was a copy of list1 (myList).
myList = [1,2,3,4,5,(1,2),(3,4)]
def onlyTuples(list1):
list2 = list1 # here is my question
for index,e in enumerate(list2):
if type(list2[index]) is not tuple:
list2[index] = (list2[index],)
return(list2)
print(myList)
create_new_list = onlyTuples(myList) # triggered by this call
print(myList)
It's all good if I change list2 = list1 to list2 = list(list1) and myList won't be changed when calling the function, but why?
The same thing doesn't happen with something like this:
a = 6
b = a
b = 7
print(a)
Any light upon the question will be appreciated. Thanks!
In python lists are passed by reference, so when you pass list to a function you pass its address in the memory. list2 = list1 won't create a copy of the list, it will save in list2 the address saved in list1. so change of list2 will change list1, but the function in the class list doesn't save the address, it copy a sequence to a list
To make a copy of a list, use:
newList = myList.copy()

The append() method issue of list in Python3

for example,i got a list:
mylist = [1,2,3]
we all know append() can add a new item at the end of the list like that:
mylist.append(4)
now the mylist is [1,2,3,4]
my issue is what happened when mylist append itself????
mylist.append(mylist)
at first i think it will look like this:
[1,2,3,4,[1,2,3,4]]
but when i print it, output is [1,2,3,4,[...]],so i print the mylist[5] and it's same to the mylist:[1,2,3,4,[...]]
so you can loop the last item of list endless,and the last item always be the same to original mylist!!!!!
anyone can tell me why is that????????
Because you aren't appending a copy of the list, but the actual list object itself. Consider this program:
mylist = [1,2,3,4]
mylist.append(mylist)
assert id(mylist) == id(mylist[4])
The final item of the list is a reference to the list itself, so you have a fully recursive, self-referential data structure.
If you want the result [1,2,3,4,[1,2,3,4]], then you need to append a copy of the original list, like so:
mylist = [1,2,3,4]
mylist.append(list(mylist))
assert mylist == [1,2,3,4,[1,2,3,4]]
It's doing that because you're telling Python to append a list(my_list) to a list. If you want to extend the list with the contents of the list, you can do this:
new_list = old_list + new_list
output: [1, 2, 3, 4, 1, 2, 3, 4]
or you can use the extend method.
old_list.extend(my_list)
Which will modify the old_list in place.

Relationship between elements of two list: how to exploit it in Python?

SO here is my minimal working example:
# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# Then I want to have these items all shuffled around, so for instance
list2 = np.random.permutation(list2)
#Now here is my problem: I want to understand which element of the new list2 came from which element of list1. I am looking for something like this:
list1.index(something)
# Basically given an element of list2, I want to understand from where it came from, in list1. I really cant think of a simple way of doing this, but there must be an easy way!
Can you please suggest me an easy solution? This is a minimal working example,however the main point is that I have a list, I do some operation on the elements and assign these to a new list. And then the items get all shuffled around and I need to understand where they came from.
enumerate, like everyone said is the best option but there is an alternative if you know the mapping relation. You can write a function that does the opposite of the mapping relation. (eg. decodes if the original function encodes.)
Then you use decoded_list = map(decode_function,encoded_list) to get a new list. Then by cross comparing this list with the original list, you can achieve your goal.
Enumerate is better if you are certain that the same list was modified using the encode_function from within the code to get the encoded list.
However, if you are importing this new list from elsewhere, eg. from a table on a website, my approach is the way to go.
You could use a permutation list/index :
# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# Then I want to have these items all shuffled around, so for instance
index_list = range(len(list2))
index_list = np.random.permutation(index_list)
list3 = [list2[i] for i in index_list]
then,with input_element:
answer = index_list[list3.index(input_element)]
Based on your code:
# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# made a recode of index and value
index_list2 = list(enumerate(list2))
# Then I want to have these items all shuffled around, so for instance
index_list3 = np.random.permutation(index_list2)
idx, list3 = zip(*index_list3)
#get the index of element_input in list3, then get the value of the index in idx, that should be the answer you want.
answer = idx[list3.index(element_input)]
def index3_to_1(index):
y = list3[index]
x = np.log(y)/np.log(2) # inverse y=f(x) for your operation
return list1.index(x)
This supposes that the operations you are doing on list2 are reversible. Also, it supposes that each element in list1 is unique.

Categories

Resources