I want to be able to interate both list1 = list('asdf')
and list2 = list('qwer')
at the same time. What is the best approach?
for i, p in list1, list2:
print(i,p)
Where i
would be increment list1
and p
would be increment list2
.
Yes, the += operator allows adding more than just a single value at a time. Anything on the right-hand side of the += will be evaluated, and then it will be added to the variable which is then updated to that new value.
Because strings, like integers, are immutable in Python, we can use the augmented assignment operator to increment them.
To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.
It works by getting the first character of each string and recursively shuffling the rest and adding this character to each element in the list. When there is one character remaining on each of the strings it returns a list where the character is added in each position of the other string.
Use zip
(or itertools.izip
if the two lists are large):
for i, p in zip(list1, list2):
print(i, p)
Alternately, if list1
might not be the same length as list2
use izip_longest
from itertools
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With