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]
Related
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 11 months ago.
i am using this code and i want to remove all the 2's from the array arr .
but when i am running it is returning me [2,2,2,"string"]
arr = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,"string"]
for i in arr:
if i == 2:
arr.remove(i)
print(arr)
The general rule of thumb is: Don't try to mutate the list you are iterating. Check this question :)
If you want to modify the list while iterating it. You may try this:
arr = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,"string"]
for i in arr[:]:
if i == 2:
arr.remove(i)
With list comprehension, we can make this better and more pythonic:
arr = [element for element in arr if element != 2]
try like this:
arr = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, "string"]
arr2 = [n for n in arr if n is not 2]
print(arr2)
This question already has answers here:
Issue with reversing list using list.pop()
(4 answers)
How do I reverse a list or loop over it backwards?
(37 answers)
Closed 1 year ago.
In the tutorial video I was watching the range used in for loop was "range(len(l))" which successfully reversed the list.
But I guess simply putting " l " will solve the purpose and it didn't can someone please tell me why is that?
def reversed_list(l):
rev = []
for i in l:
l_popped = l.pop()
rev.append(l_popped)
return rev
SAMPLE_LIST = [1,2,3,4]
print(reversed_list(SAMPLE_LIST))
OUTPUT:
[4, 3]
I'm not sure what the tutorial you watched did, but range(len(_)) will not reverse, it just creates a range of the size of your list, starting at 0.
If you want to reverse a list in Python, just use the builtin reversed:
l = list("hello")
print(list(reversed(l))) # at list to have an actual list as opposed to an iterator
# ['o', 'l', 'l', 'e', 'h']
print(range(len(l)))
# range(0, 5)
PS: The reason your solution doesn't work is you're changing the object you iterate over during the iteration by using pop. A simple way to debug this is to add a print statement:
def reversed_list(l):
rev = []
for i in l:
print("This is l:", l)
l_popped = l.pop()
rev.append(l_popped)
return rev
print(reversed_list([1,2,3,4]))
# This is l: [1, 2, 3, 4]
# This is l: [1, 2, 3]
# [4, 3]
This loop is root cause of problem.
for i in l:
l_popped = l.pop()
rev.append(l_popped)
return rev
Let us try to dry run.
When i = 1 (index 0), it pops 4 and rev = [4], l = [1, 2, 3]
When i = 2 (index 1), it pops 3 and rev = [4, 3], l = [1, 2]
Now, index crosses the length of l hence operation on remaining elements are not executed.
If you really want to use pop to reverse a list, you can make a shallow copy of the original list. Every time you iterate, the length of the list reduces
>>> x=[1,2,3,4]
>>> z=x.copy()
>>> y=[x.pop(i) for i in range(len(z)-1,-1,-1)]
>>> y
[4, 3, 2, 1]
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/
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
This question already has answers here:
Index all *except* one item in python
(11 answers)
Closed 5 months ago.
I am new to python and am trying to create a copy of a list without a certain element. This is how I am doing it at the moment:
oldList[1,23,4,3,5,345,4]
newList = oldList[:]
del newList[3]
doSomthingToList(newList)
I was wondering if there is a better more eloquent way to do this, instead of copying the list and then deleting the element in two lines?
oldList[1,23,4,3,5,345,4]
newList = oldlist[:3] + oldList[4:]
doSomthingToList(newList)
Using list comprehension:
>>> oldList = [1,23,4,3,5,345,4]
>>> newList = [x for i, x in enumerate(oldList) if i != 3] # by index
>>> newList
[1, 23, 4, 5, 345, 4]
>>> newList = [x for x in oldList if x != 4] # by value
>>> newList
[1, 23, 3, 5, 345]
Try this with 'slicing':
>>> oldList = [1, 2, 3, 4, 5]
>>> newList = oldList[:2] + [oldList[3:]
>>> newList
[1, 2, 4, 5]
Consider using the built-in function filter
oldList = [1, 2, 3, 4, 5]
newList = filter(lambda number: number != 3, oldList)
# newList == [1,2,4,5]
filter's arguments are function, iterable. It applies the function you give it to every element of the iterable and returns a list of the elements that the function returns True on.