Home > database >  Using a for-loop, in another for-loop, to iterate through a list of lists
Using a for-loop, in another for-loop, to iterate through a list of lists

Time:11-29

I'd like to write a set of for-loops that iterate through a list of lists as shown below.

pathways = ['pathway_1','pathway_2']

pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']

for i in pathways:
    for ii in i:
          print(ii)

I'd like the output to look like this:

gene_A
gene_B
gene_C
gene_D

but currently generates this:

p
a
t
h
w
a
y
_
1
p
a
t
h
w
a
y
_
2

Is there a simple way of achieving this?

CodePudding user response:

In the outside loop you are looping over a string and not a list, change the code like this:

pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']

pathways = [pathway_1, pathway_2]

for i in pathways:
    for ii in i:
          print(ii)

CodePudding user response:

You cannot use strings variables, so remove '', else you loop by letters from strings in pathways list:

pathways = [pathway_1,pathway_2]
  • Related