Reputation: 519
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
Upvotes: 0
Views: 83
Reputation: 8508
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
Upvotes: -1
Reputation: 30268
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.
Upvotes: 3
Reputation: 1707
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]
Upvotes: 0
Reputation: 350
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]
Upvotes: 0