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
  • 45,728
  • 6
  • 46
  • 64
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']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114