A
A
aarne_sf2021-09-08 03:19:14
Python
aarne_sf, 2021-09-08 03:19:14

Is it possible to add 2 arrays to a for loop?

a = [1,2,3]
b=['a','b','c']
for i in a,b:
   print(str(a)+"swap"+b)

How to add 2nd array in in for loop?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2021-09-08
@sanya84

There is a built-in function for thiszip

aa = [1,2,3]
bb=['a','b','c']


for a, b in zip(aa, bb):
   print(str(a)+"swap"+b)

zip() documentation

D
dollar, 2021-09-08
@dollar

Depending on how you need to sort through, in what order. If you need to show the i-th element from
for each i -th element from , then they will have a common index, and you need to focus on it:ab

example
a = [1,2,3]
b = ['a','b','c']

i = 0
while i < len(a):
    print(str(a[i])+" swap "+b[i])
    i += 1

If you need to pair everyone with everyone, then just two nested loops:
example
a = [1,2,3]
b = ['a','b','c']
for i in a:
    for j in b:
        print(str(i)+" swap "+j)

A
alekssamos, 2021-09-08
@alekssamos

>>> a = [1,2,3]
>>> b=['a','b','c']
>>> for i in zip(a,b):
...    print(str(i[0])+"swap"+i[1])
...
1swapa
2swapb
3swapc
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question