0
A = [['2','4'],['1','2']]
B = []
for i in A:
  for x in A[i]:
    B.append(x)
print(B)

TypeError: list indices must be integers or slices, not list

I expected to use two loops to iterate all the elements in A. A[i] is the first list element in A. And the second for loop should iterate the A[i] and append all the elements into B. However, the error says must be integers or slices, not list. I don't know why i can not iterate elements in A[i]. I am very appreciate if anyone can help.

Nick Parsons
  • 38,409
  • 6
  • 31
  • 57
DanielDDD
  • 31
  • 4

1 Answers1

0

Try using just i:

A = [['2','4'],['1','2']]
B = []
for i in A:
  for x in i:
    B.append(x)
print(B)

Or use list comprehension:

A = [['2','4'],['1','2']]
print([x for i in A for x in i])

Both output:

['2', '4', '1', '2']
U12-Forward
  • 65,118
  • 12
  • 70
  • 89