If I want to iterate through a list with a for loop, I can do something like:
elements = [1,2,3,4,5,6,7,8,9,10]
for element in elements:
print(element)
and it will output:
1
2
3
4
5
6
7
8
9
10
But I am curious, is there any ways that I can have the loop tell me what is not currently being iterated?
For example:
when element is 1, it can output a list that looks like this [2,3,4,5,6,7,8,9,10], and when the loop goes on, each round it will output something like:
[1,3,4,5,6,7,8,9,10]
[1,2,4,5,6,7,8,9,10]
[1,2,3,5,6,7,8,9,10]
[1,2,3,4,6,7,8,9,10]
[1,2,3,4,5,7,8,9,10]
[1,2,3,4,5,6,8,9,10]
[1,2,3,4,5,7,8,9,10]
[1,2,3,4,5,6,7,9,10]
[1,2,3,4,5,6,7,8,10]
[1,2,3,4,5,6,7,8,9]
Thanks in advance.
>Solution :
Use enumerate(<iterable>) and print the two parts of the list, skipping the relevant element.
elements = [1,2,3,4,5,6,7,8,9,10]
for i, element in enumerate(elements):
print(elements[:i] + elements[i+1:])
(Note how you won’t get an IndexError, since it’s a slice. elements[i+1] would result in an IndexError; a slice will yield an empty list.)
A solution without enumerate(), and with filter():
for element in elements:
print(list(filter(lambda x: x != element, elements)))
(You’ll need list(...), unfortunately, since filter() is evaluated lazily, that is, it will only yield the elements if it’s actually iterated over. print() doesn’t do that, but list() does.)
This is roughly the same as some other solutions shown here, which use a list comprehension. Some people prefer filter, but I think it’s deemed slightly more Pythonic to use a list comprehension. But very much a personal preference:
for element in elements:
print([item for item in elements if item != element])
A big caveat to the non-enumeration methods: this only works when the list values are unique, since they compare values, not the list index. If there are duplicate items in the list, the output likely won’t be what you want.