Remove and add items to iterated lists [duplicate] - python

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I am iterating through two lists like so:
list1 = [z]
list2 = [z-t,z-s,s-a,a-n, g-z]
for e in list1:
for t in list2:
# if item from list2 contains item from list1 (before "-")
# remove the item from list2 and append part after "-" to list1
# iterate again until no change is made or list2 is empty
The problem I can't solve is that when I remove the item from list2 it goes to next item and I am not able to prevent it. For example
list2 = [z-t,z-s,s-a....]
^ removing this while iterating
next iteration jumps over one item
list2 = [z-s, s-a,...]
^ this is where I am second iteration
list2 = [z-s, s-a,...]
^ this is where I want to be
Is there any way to do this?

There are a few ways to achieve this, one is iterating backwards over the list, ie
for e in list1:
for t in list2[::-1]: # This iterates over the list backwards
# Do your check
# Remove the element
If you need to process it forwards, you can iterate over a copy so you can mutate the original list while iterating over the initial content, ie
for e in list1:
for t in list2[:]: # The [:] syntax feeds you your data via a new list.
# Do your check
# Remove the element, and not worry about mutating the original list length

Related

Removing certain elements from a list that start with a specific character and adding them to new list in Python [duplicate]

This question already has answers here:
Checking whether a string starts with XXXX
(5 answers)
Apply function to each element of a list
(4 answers)
Closed 3 months ago.
I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements.
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
list1 becomes:
list1 = ['midterm', 'school']
new list that was created from removing the elements that had '[x]' in the front:
new_list = ['final', 'gym', 'class']
I am new to coding and am having difficulties with this.
Since you are a beginner, the verbose way to do this is the following
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = []
for s in list1:
if s.startswith("[x]"):
new_list.append(s[3:])
print(new_list)
However, you can take advantage of Python's list comprehension to do it in a single line, like this
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = [s[3:] for s in list1 if s[0:3] == "[x]"]
print(new_list)
Both methods yield ['final', 'gym', 'class']

How do I check if a list contains all the elements of another list in Python? It's not working [duplicate]

This question already has answers here:
Checking if List contains all items from another list
(3 answers)
Closed 1 year ago.
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = item in List2 for item in List1
if check is True:
print("The list {} contains all elements of the list {}".format(List1, List2))
Why is this damn thing not working? Also is checkif = item in list2 for item in list1 a list comprehension or what?
Someone please correct my code, thanks.
I think you want all:
list1 = ['Gryffindor', 'Ravenclaw', 'Hufflepuff', 'Slytherin']
list2 = ['Gryffindor', 'Ravenclaw']
checkif = all(item in list1 for item in list2)
Also, you need to swap list1 and list1 to get the result you describe in the print line.
You can use sets here and specifically check the relationship whether one of your sets is a subset of the other:
set(list2).issubset(list1) # True
To use this the first object must be a set hence set(list2) but the second can be any iterable. One caveat here is that since we're comparing sets, it will only check for unique elements, i.e. it will not care about repeated values.

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
[]

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] = []

Generate all combinations from multiple lists with repeat lists

I have multiple lists, some of them are repeats and I need all combinations, excluding ones where the same element from a repeated list is chosen. For example, I have
import itertools
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [4,5,6]
list4 = [7,8,9]
a = [list1,list2,list3,list4]
print list(itertools.product(*a))
which outputs
(1,4,4,7)
(1,4,4,8)
(1,4,4,9)
(1,4,5,7)
.
.
.
etc, as you'd expect, but what I want it to do is output every combination, without repeating elements from lists 2 and 3. Like this:
(1,4,5,7)
(1,4,5,8)
(1,4,5,9)
(1,4,6,7)
(1,4,6,8)
(1,4,6,9)
(1,5,6,7)
(1,5,6,8)
(1,5,6,9)
(2,4,5,7)
.
.
.
I'd obviously like to avoid having to remove them manually after creating the list, but any help on how to do this efficiently is really appreciated. Thanks.
The easy way is a generator expression with a filter:
print list(item for item in itertools.product(*a) if item[1] != item[2])
If two items are considered the same if they contain the same elements, and if each item is guaranteed to contain no repeated elements, you can discard duplicates by changing them into sets and only adding them to your list if they're not already in it:
result = []
for item in itertools.product(*a):
if item[1]==item[2]:
continue
item = set(item)
if item not in result:
result.append(item)
print result

Categories

Resources