Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exclusive loop [duplicate]

Tags:

python

I want to loop through a list and separate the current element from others. Like this :

for e in the_list:
    function_call(e, <the_list but e>)

Is there an elegant way to do that ?

like image 948
Abdelhamid Belarbi Avatar asked Dec 21 '22 06:12

Abdelhamid Belarbi


2 Answers

You could use enumerate and slice the list:

for index, elem in enumerate(the_list):
    function_call(elem, the_list[:index] + the_list[index + 1:])
like image 64
Blender Avatar answered Jan 01 '23 19:01

Blender


A nice solution that reads (reasonably) well and doesn't need messing around with indices.

>>> from itertools import combinations
>>> data = [1, 2, 3, 4]
>>> for item, rest in zip(data, 
                          reversed(list(combinations(data, len(data)-1)))):
...     print(item, rest)
... 
1 (2, 3, 4)
2 (1, 3, 4)
3 (1, 2, 4)
4 (1, 2, 3)
like image 44
Gareth Latty Avatar answered Jan 01 '23 18:01

Gareth Latty