Introduction to Python - Help me understand simple execution [duplicate] - python

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 6 years ago.
>>> def double(x):
x += x
>>> a=[1,2,3,4]
>>> b=a
>>> double(b)
>>> print(a)
[1, 2, 3, 4, 1, 2, 3, 4]
>>> print(b)
[1, 2, 3, 4, 1, 2, 3, 4]
>>>
Could someone help me understand how the a list got doubled in this process? I understand how b's list doubled but not a
Thank you!

I think this is what your code looks like:
def double(x):
x += x
a=[1,2,3,4]
b=a
double(b)
print(a)
print(b)
Output:
[1,2,3,4,1,2,3,4]
[1,2,3,4,1,2,3,4]
And the reason is simply that if you have a list x = [1,2,3] and a list y = [6,7,8], then x + y gives you [1,2,3,6,7,8]. So the line x += x adds the elements of x to the end of itself, doubling it.
The reason that a doubles when b doubles is because python lists are mutable. You can find out more here: https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/

Related

Python array sorting with unexpected result [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 1 year ago.
def sorted():
print(numList)
sortedList=numList
sortedList.sort()
print(numList)
print(sortedList)
Result:
[4,1,9,16,25]
[1,4,9,16,25]
[1,4,9,16,25]
Actually, I just sort the "sortedList" only, but result shows it sorted numList too. may I know the reason and solution.
You need to make a copy of the list, otherwise it is a pointer to the list and will act on both things.
https://www.programiz.com/python-programming/methods/list/copy
Here's how copy works. You'll want to copy your numList into sortedList and then sort it.
Example:
lst = [0, 1, 2, 3]
lst2 = lst
lst2[0] = 4
lst
>>> [4, 1, 2, 3]
Versus
lst = [0, 1, 2, 3]
lst2 = lst.copy()
lst2[0] = 4
lst
>>> [0, 1, 2, 3]

How is `:` interpreted? [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 2 years ago.
I know "how" to use the : operator to extract data from a list in python.
Eg:
l = [1,2,3]
print(l[0:1])
print(l[-1:])
Yields:
[1]
[3]
But, how does python literally interpret the :?
Why can't I set a variable equal to : and then call it?
Eg:
x = :
print(l[x])
Would yield:
[1, 2, 3]
Hoping someone who can go deeper on how python works can offer some insight.
Thanks!
: is shorthand for the slice class. You can assign instances of that class to variables for what you're trying to:
>>> l = [1, 2, 3]
>>> l[1:3]
[2, 3]
>>> l[slice(1, 3)]
[2, 3]
>>> x = slice(0, 2)
>>> l[x]
[1, 2]

Changing lists in Python [duplicate]

This question already has answers here:
python: mutating the copy of a list changes the original?
(1 answer)
Why should I refer to "names" and "binding" in Python instead of "variables" and "assignment"?
(5 answers)
Closed 3 years ago.
#Case 1
myList=[1,2,3,4]
old=myList
myList=[5,6,7,8]
print(old)
#Case 2
myList=[1,2,3,4]
old=myList
myList[0]=10
print(old)
#Case 3
myList=[1,2,3,4]
old=myList.copy()
myList[0]=10
print(old)
[1, 2, 3, 4]
[10, 2, 3, 4]
[1, 2, 3, 4]
For me the case 3 is the safe case and Case 2 is clear. However, I am not able to clearly understand why in case 1 old is not changed.
In case 1, we are re-assigning a brand new list to the name myList. The original list that was assigned to myList is not affected by this operation; myList is now simply pointing to a different object
This becomes clear when we look at the ids of the objects:
>>> myList = [1,2,3,4]
>>> print(id(myList))
47168728
>>> old = myList
>>> print(id(old))
47168728
>>> myList = [5,6,7,8]
>>> print(id(myList))
47221816
>>> print(id(old))
47168728
Writing old = myList does not bind the two variables inextricably; it assigns the value of myList to old at that point in time. By reassigning myList to a new list afterwards, you are then making myList and old point to different values.

Why is append and concat giving me different results? [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 3 years ago.
I have a function that generates all permutations of a string. It prints out all the possible permutations just fine. But now I want a list of all such permutations.
I tried making the global list as well as tried passing it as a parameter, but post appending the permutation all the lists previously in the main list get changed to the list last appended. Please explain this behavior
def permutationNum(a,lower,upper,perm):
if(lower==upper):
print(a)
print(perm)
perm.append(a)
# perm = perm.append(a)
else:
for i in range(lower,upper+1):
a[lower],a[i] = a[i],a[lower]
permutationNum(a,lower+1,upper, perm)
a[lower],a[i] = a[i],a[lower]
listy = [1,2,3]
perm = []
permutationNum(listy, 0, len(listy)-1, perm)
print(perm)
Output : [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
Expected Output : [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
UPDATE:
Turns out it was indeed deep copy problem after all. I just had a temp variable store a deep copy of a and appended that temp variable to the list. It all worked out.
In python, certain data types are copied when passed into functions as arguments, while others are referenced.
If an argument is copied, any changes to it inside the function will not affect the original variable that was passed in.
If an argument is referenced, any changes to it inside the function will affect the original.
Strings, Ints, Floats are copied, while objects and lists are referenced. This behaviour is also replicated when assigning one variable to another:
a = 5
b = a
b = 6
print(a)
>>> 5
a = [5]
b = a
b.append(6)
print(a)
>>> [5, 6]
If you want to copy a list and not just reference it, there's multiple ways you can achieve this:
Copy Module
import copy
a = [5]
b = copy.copy(a)
b.append(6)
print(a)
>>> [5]
Slicing
a = [5]
b = a[:]
b.append(6)
print(a)
>>> [5]
.copy()
a = [5]
b = a.copy()
b.append(6)
print(a)
>>> [5]
list()
a = [5]
b = list(a)
b.append(6)
print(a)
>>> [5]
So in your case, you would change the following line from:
permutationNum(a,lower+1,upper, perm) to
permutationNum(a[:],lower+1,upper, perm)
Change this line - to append new instance of list everytime
perm.append(list(a))
Another way to get permutations:
import itertools
def permutationNum(a):
for x in itertools.permutations(a):
perm.append(list(x))
listy = [1,2,3]
perm = []
permutationNum(listy)
print(perm)
or
import itertools
def permutationNum(a):
return [list(x) for x in itertools.permutations(a)]
listy = [1,2,3]
print(permutationNum(listy))

How do I make a function that returns a list of unique strings, given a list of strings with duplicates? [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 8 years ago.
This is a piece of homework for my programming course. We are asked to make a function that accepts a list of strings as a parameter, and then returns the same list of strings but without duplicates.
e.g:
>>> unique_list(['dog','cat','dog','fish'])
['dog','cat','fish']
Any information regarding the matter would be greatly appreciated.
Use the following code:
>>> def unique_list(mylist):
... copy = []
... for k in mylist:
... if k not in copy:
... copy.append(k)
... return copy
...
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 3, 2]
>>> unique_list(['dog','cat','dog','fish'])
['dog', 'cat', 'fish']
The for loop loops over every item in mylist. If the item is already in copy, it does nothing. Otherwise, it adds the item to copy. At the end, we return the 'unduplicatified' version of mylist, stored in copy.
Or a one-liner would be:
>>> def unique_list(mylist):
... return list(set(mylist))
...
>>> unique_list([1])
[1]
>>> unique_list([1, 1])
[1]
>>> unique_list([1, 1, 2])
[1, 2]
>>> unique_list([1, 3, 1, 2])
[1, 2, 3]
>>> unique_list(['dog','cat','dog','fish'])
['fish', 'dog', 'cat']
def unique_list(subject):
return list(set(subject))
This is what you can write in python 3.3

Categories

Resources