0

I have a 'for' loop where I need t iterate through a list but do not need the iterative variable named 'node'. What would be a more elegant way to do this?

for node in NODES:
    if i % 2 == 0:
        tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
    i += 1
winteralfs
  • 459
  • 6
  • 25

4 Answers4

3

Looks like this is a case of actually needing the index in NODES. You get this using range(len(NODES)) but range() also supports an optional parameter of step that would allow you step through this 2 at a time (note: you also have to include the start if you want the step):

for i in range(0, len(NODES), 2):
    tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]

This assumes there is an even number of entries in the list and will raise an IndexError if it isn't.

Alternatively, if all you are trying to do is step through the list 2 at a time you could also use:

it = iter(NODES)
for k, v in zip(it, it):
    tex_pairs_to_swap_dict[k] = v

This is equivalent to the above without creating the it variable:

for k, v in zip(*[iter(NODES)]*2):
    tex_pairs_to_swap_dict[k] = v

This will silently ignore the last value in an odd sized list.

AChampion
  • 29,683
  • 4
  • 59
  • 75
0

The most effective way to do this would be to use a range. I would recommend you do this:

for i in range(len(NODES)):
    if i % 2 == 0:
        tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
The Grand J
  • 348
  • 2
  • 5
  • 14
0

You can use the enumerate function, which returns a tuple with the index and the item.

for i, _ in enumerate(NODES):
    if i % 2 == 0:
        tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
Safwan Samsudeen
  • 1,645
  • 1
  • 10
  • 25
-1

In python you can define a for loop without a variable and still access the contents of that. For example:

x = [1,2,3]

for _ in x: print (_)

will provide you an output of:

1
2
3

You can also do this with dictionaries. For example:

x = {1:10, 2:20}

for _,__ in x.items(): print (_,__)

The output of this will be:

1 10
2 20

In summary, you can use _ as a variable and reference it. While you may think there is no variable defined, it is still a throwaway variable. More details about _ can be found in this post: What is the purpose of the single underscore "_" variable in Python?

Based on this, you can rewrite your code as follows:

for _ in NODES:
    if i % 2 == 0:
        tex_pairs_to_swap_dict[NODES[i]] = NODES[i+1]
    i += 1

With this, you don't need to use the variable node

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33