Delete list elements after using them [duplicate] - python

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I have a list
test_list = [1,2,3,4,5]
I want to iterate over the elements of this list and delete them after using. But when I try to do this
for element in test_list:
print element
test_list.remove(element)
Alternate elements are printed and removed from test_list
1
3
5
print test_list
[2, 4]
Please explain why this happens!

Read the answers to strange result when removing item from a list to understand why this is happening.
If you really need to modify your list while iterating do this:
>>> items = ['x', 'y', 'z']
>>> while items:
... item = items.pop()
... print item
...
z
y
x
>>> items
[]
Note that this will iterate in reverse order.

in python this concept is called an iterator
my_iter = iter(my_list)
each time you consume or look at an element it becomes gone ...

Related

Remove or pop is not eliminating all the elements [duplicate]

This question already has answers here:
Why does Python skip elements when I modify a list while iterating over it?
(8 answers)
Closed 2 years ago.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop() also but couldn't remove all elements
The reason why you are not able to remove all the elements is that when you are removing an element from the array the j value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
Output
3
5
[4,6]
As you can see in this output print(j) does not print all the elements, it only prints 3 and 5. So only 3 and 5 are removed.
How to solve it?
So you can either use clear(), like this
lis.clear()
Or if you want to use iteration you can do it with pop() like this
for i in range(len(lis)):
lis.pop(i)
Or you can create a shallow copy of the list and remove() the elements one by one like this
for i in list(lis):
lis.remove(i)
Or you can use : to return the whole slice of the array (copy of the array)
for i in x[:]:
x.remove(i)
use clear to clear all the element of the list
lis =[3,4,5,6]
lis.clear()
print(lis)
Output:
[]
A correct solution will be to create a shallow copy with the help of list() function.
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
Output
[]

Check if item is in list of list [duplicate]

This question already has answers here:
Check if an item is in a nested list
(8 answers)
Closed 2 years ago.
I'm looking to see if item is in list of list.
List1 = [['a','b','c'],['d','e','f'],['g','h','i']]
If b is in any of the list in a list, then print True. Else, print False.
What's the pythonic way to do this?
Try this:
# check element exists in list of list or not?
result = any("b" in sublist for sublist in List1)
# printing result
print(str(result))
I'll play the fool...
>>> 'b' in sum(List1, [])
True
>>> 'B' in sum(List1, [])
False

How can I remove multiple elements from a list? [duplicate]

This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []

How do I check if a sublist in a 2D list is in a list? [duplicate]

This question already has answers here:
Check if list contains another list in python
(2 answers)
Closed 6 years ago.
I have two lists:
my_list = [1,2,3,4,5]
my_new_list = [[1,3,7,5],[1,2,3,4,5]]
How can I check that a sublist equals my_list?
If you want to check if my_list is in the my_new_list just use in:
>>> my_list in my_new_list
True
If you want to know the index of the matching list you can use index:
>>> my_new_list.index(my_list)
1
If you think these are too efficient, too easy or too short you can do it manually as well:
>>> any(sublist == my_list for sublist in my_new_list) # equivalent to "in"
True
>>> next(idx for idx, sublist in enumerate(my_new_list) if sublist == my_list) # like "index".
1
You can index built-in function
>>> my_new_list.index(my_list)
1
Or you can use in :
>>> my_list in my_new_list
True
You can also use magic function contains
>>> my_new_list.__contains__(my_list)
True

append function in python [duplicate]

This question already has answers here:
Ellipsis lists [...] and concatenating a list to itself [duplicate]
(3 answers)
Closed 6 years ago.
I have a list X = ['xyz']
I use the below commands for appending to another variable.
L = X
L.append(X)
L
Out[109]: ['xyz', [...]]
I am unable to understand why the second element in the new L list is not having the value as 'xyz'
My question is not how to append or extend a list, but in fact about the functionality of Append function, which has been correctly explained by #sinsuren below.
append add X as an element to L. If you want the element inside X to be inserted to L, use extend instead:
>>> X = ['xyz']
>>> L = X
>>> L.extend(X)
>>> L
['xyz', 'xyz']
Try this, it will extend the list.
L.extend(X)
But if you want to use append. Use a element like this L.append('abc'). It will give same result or L.append(X[0])
Edit: You have Appended list to itself. It will recursively append to itself and due to which even L[1] will give you same response. Like L[1] = ['xyz', [...]] . and for more understanding Please refer What's exactly happening in infinite nested lists?

Categories

Resources