I don't understand the difference between these codes [duplicate] - python

This question already has answers here:
Difference between del, remove, and pop on lists
(14 answers)
Closed 2 years ago.
data = [2, 4, 3, 1, 5, 10, 9]
data.pop()
print(data)
result: [2, 4, 3, 1, 5, 10]
the above is what i think makes sense
however,
data = [2, 4, 3, 1, 5, 10, 9]
Print(data.pop())
I got this
Result : 9
what is the difference?

In the 1st situation, you are printing a list of data. I have re-lined the code and added comments to make it more understandable:
Scenario 1:
data = [2, 4, 3, 1, 5, 10, 9] # the given data list
data.pop() # pop the last element off the list
print(data) # print 'data' (which is the list)
The reason why the result here is [2, 4, 3, 1, 5, 10] is because you are popping from the list, and then printing the list itself.
Scenario 2:
data = [2, 4, 3, 1, 5, 10, 9] # the given data list
print(data.pop()) # print the value returned by data.pop(), which is 9
# Result : 9
List.pop() is a method that returns the popped value from the list. So, by doing print(data.pop()), you are requesting to print the single popped value rather than the data list in its entirety.
See the Python documentation on the List.pop() method here.

The pop() method returns the value which was deleted from the list.
If you try to print that d.pop() it just returns the removed value.

When you use pop( ) it returns the last element of the list and internally it deletes last element from the list.
Note that in the first code you’re printing data ( the list ) and in the second one you’re printing what pop returns

Related

Getting the value of List and sum in python

I newbie in python and I have a trouble how can I make my loop with that shape below and getting the total number of each line, I tried the code below but it seems it doesn't right
I should use list in loop like the declaration below, I appreciate who can help me.
data = [1, 2, 3, 4, 5]
Expected output:
[1, 2, 3, 4, 5, 15]
[2, 3, 4, 5, 14]
[3, 4, 5, 12]
[4, 5, 9]
[5, 5]
This is what I tried but it doesn't use list ,I think it's wrong
data = 5
for i in range(data):
for j in range(i+1):
print("[",j+1, end=" "+" ]")
print("[ ]")
Usually in these kind of exercises you shouldn't build the string yourself(talking about brackets). Those brackets are part of the representation of the lists in Python. So build your list object and the final result is gonna be printed as you expected. So don't attempt to put individual numbers, spaces, brackets together yourself.
You can use:
data = [1, 2, 3, 4, 5]
for i in range(len(data)):
slice_ = data[i:]
print(slice_ + [sum(slice_)])
Explanation:
Basically in every iteration, you create a slice of the list by specifying the start point to the end. Start point comes from the range(len(data)) range object.
first iteration : From index 0 to end.
second iteration: From index 1 to end.
...
Then you concatenate the slice with the sum of the slice. But you have to put the sum inside a list because a list can't be concatenated with an int. Of course other option is to .append() it before printing:
for i in range(len(data)):
slice_ = data[i:]
slice_.append(sum(slice_))
print(slice_)

Python List Del & Reconciliation [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I'm trying to delete multiple elements from a list.
The elements are having their indexes evaluated dynamically, and stored in a list called "dstry". It may look something like this:
arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]
However, if I do...
for i in dstry:
del arr[i]
The list begins to shrink, and dstry's target elements are no longer where they should be.
Logically, how can I get around this? It'd be nice if the del could resolve all at once and delay the collapse of the array. Should I instead replace the elements with a flag value and then del them wherever they appear later so that index is not a factor?
Thanks
A bit creative solution, but this should fix the problem with the index you had.
arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2]
dstry = [1, 2, 9]
x=len(arr)
for i in dstry:
del arr[-x+i]
print(arr)

Python - iterating over lists

I want my code's 2nd function to modify the new list made by my 1st function.
If I am understanding things correctly giving a list as an argument will give the original list (my_list in this case).
so the code removes 1 & 5 and then adds 6, but not 7?
my_list = [1, 2, 3, 4, 5]
def add_item_to_list(ordered_list):
# Appends new item to end of list which is the (last item + 1)
ordered_list.append(my_list[-1] + 1)
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for items_to_remove in ordered_list:
ordered_list.remove(items_to_remove)
if __name__ == '__main__':
print(my_list)
add_item_to_list(my_list)
add_item_to_list(my_list)
add_item_to_list(my_list)
print(my_list)
remove_items_from_list(my_list, [1,5,6])
print(my_list)
output of
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 4, 6, 8]
instead of wanted
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 7, 8]
Thank you and sorry for the elementary question
In your remove_items_from_list function you are iterating through the wrong list. You should iterate through every item in the items_to_remove list like this:
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for item in items_to_remove:
ordered_list.remove(item)
This will now iterate through each item in the remove list and remove it from you ordered_list.
There is a bug in the remove_items_from_list function. For it to achieve what you want it should go:
def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
for item in items_to_remove:
ordered_list.remove(item)
As a side note, your code has incorrect number of blank lines before function definitions. Should be two blank lines before the function, and not more than one blank line inside functions. It seems not to have affected the code for now, but makes it harder to read, and could cause problems in future.
In the second function you want to iterate over items_to_remove (and not your original list) and then remove every item.
Use:
def remove_items_from_list(ordered_list, items_to_remove):
for item_to_remove in items_to_remove:
ordered_list.remove(item_to_remove)
And don't change the a list when you are iterating over it,which may cause bug.

why 2 and 4 remain in the 2 example? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I need to remove all unique objects in the given lists.
My code passes 1,3,4 checks but doesn't pass 2nd one, it returns [2,4], why not []?
def checkio(data):
for i in data:
if data.count(i) == 1 :
data.remove(i)
return data
if __name__ == "__main__":
assert isinstance(checkio([1]), list), "The result must be a list"
assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"
The problem here is that you are removing elements from a list while iterating through it, which you should never do.
The iteration for i in data keeps moving the index it's looking at forward. So, when you remove the first element in the list, the next item is moved to index 0 and the loop moves on to look at the element at index 1, skipping over the item that was moved to index 0.
Instead, you can build up a new list containing items that meet your criteria:
items = []
for i in data:
if (data.count(i) > 1):
items.append(i)
return items
Or do something like this:
return [i for i in l1 if l1.count(i) > 1]
The 'remove' function automatically recreates the list. So when "1" was removed, "2" was put in that slot, so it won't check that same position again, which is why alternating items are remaining. However, you can still implement the same function as you have, but instead work from the back of the list and iterate to the front:
def checkio(data):
for i in range(len(data)-1,-1,-1):
if data.count(data[i]) == 1 :
data.remove(data[i])
return data

Pop index out of range [duplicate]

This question already has answers here:
Python: pop from empty list
(5 answers)
Closed 3 years ago.
N=8
f,g=4,7
indexList = range(N)
print indexList
print f, g
indexList.pop(f)
indexList.pop(g)
In this code I am getting an error stating that the pop index of g in indexList is out of range.
Here is the output:
[0, 1, 2, 3, 4, 5, 6, 7]
4 7
Traceback (most recent call last):
indexList.pop(g)
IndexError: pop index out of range
I don't understand, g has a value of 7, the list contains 7 values, why is it not able to return me the 7 in the list?
To get the final value of a list pop'ed, you can do it this way:
>>> l=range(8)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7]
>>> l.pop(4) # item at index 4
4
>>> l
[0, 1, 2, 3, 5, 6, 7]
>>> l.pop(-1) # item at end - equivalent to pop()
7
>>> l
[0, 1, 2, 3, 5, 6]
>>> l.pop(-2) # one left of the end
5
>>> l
[0, 1, 2, 3, 6]
>>> l.pop() # always the end item
6
>>> l
[0, 1, 2, 3]
Keep in mind that pop removes the item, and the list changes length after the pop. Use negative numbers to index from the end of a list that may be changing in size, or just use pop() with no arguments for the end item.
Since a pop can produce these errors, you often see them in an exception block:
>>> l=[]
>>> try:
... i=l.pop(5)
... except IndexError:
... print "sorry -- can't pop that"
...
sorry -- can't pop that
After you pop the 4, the list only has 7 values. If you print indexList after your pop(f), it will look like:
[0, 1, 2, 3, 5, 6, 7]
Along with all the other answers, the important part about the pop() function is that it removes the value from the array, thus changing the indexes. After popping index 4, your list is left with 7 items. It is important to know that Python indexes starting at 0 so your 7 item list only contains indexes 0 through 6. That's why popping index 7 is out of bounds, it no longer exists.
Typically a "popping" function is used when implementing a stack or a queue where the goal is to get a value from a list of values waiting to be processed. To avoid processing the same data twice by accident, you make sure to remove it at the same time as retrieval.
Sometimes stacks and queues can be implemented with a peek operation that will return just the value without removing it but since Python implements stacks and queues just using regular arrays without any special wrapper, your peek function would be the standard array[index] call.
----EDIT----
It occurs to me that it could be the case that instead of removing the item at index 7, you wish to remove the value 7. If that's the case, you should call indexList.remove(7). This will remove the first instance of 7 in your list, no matter what its index (and throws an error if there is no value 7). I'm pretty sure you understand that pop() takes an index, though.
Just in case, take a look at the Python datastructures API for more information on what functions are available, what they do, and what arguments they take.

Categories