Home > Back-end >  How can I iterate in a list with sepration of them?
How can I iterate in a list with sepration of them?

Time:01-24

I want to say

for f in x: do certain thing.

but i dont want to connect them to each other. first do a work for x[0] then for x[1] then etc.

x = ['ABCED', 'BACF', 'BCD']

for exmple, it cant seprate them by the index, it just repeate print part for all q in x. how can i fix it?

  for f in x:
        for q in f:
            print('hi')

the output that i except that is:

[[A,B,C,E,D],[B,A,C,F],[B,C,D]]

CodePudding user response:

Use list on str create a list of each character:

out = [list(i) for i in x]
print(out)

# Output
[['A', 'B', 'C', 'E', 'D'], ['B', 'A', 'C', 'F'], ['B', 'C', 'D']]

CodePudding user response:

Another alternative using map:

list(map(list, x))

CodePudding user response:

x = ['ABCED', 'BACF', 'BCD']
new_list= [list(i) for i in x]

or:

list(map(list, x))

output:

[['A', 'B', 'C', 'E', 'D'], ['B', 'A', 'C', 'F'], ['B', 'C', 'D']]
  •  Tags:  
  • Related