2

I have a list like this [1, 2, 3, [4, 5, 6]]

How can I remove [ character inside the list so I can get [1, 2, 3, 4, 5, 6]?

This is my code so far:

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    if len(item) > 1:
        for sub_item in item:
            new_a.append(sub_item)
    else:
        new_a.append(item)
print(new_a)

Then I got this error:

TypeError: object of type 'int' has no len()

But when I get the length of the inside list with len(a[3]), it returns 3.

How can I fix this?

huy
  • 1,648
  • 3
  • 14
  • 40

2 Answers2

2

Instead of using len to check whether something is a list, you should use isinstance:

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    if isinstance(item, list):
        for subitem in item:
            new_a.append(subitem)
    else:
        new_a.append(item)

See @Always Sunny's comment for even simpler ways of doing this

kingkupps
  • 3,284
  • 2
  • 16
  • 28
1

You can use extend():

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    try:
        len(item)
        new_a.extend(item)
    except:
        new_a.append(item)
print(new_a)

Or you can use type() if you want to check item is list or not:

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    if type(item) == list:
        new_a.extend(item)
    else:
        new_a.append(item)
print(new_a)
Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25