Why does .split in python not work on double bracket list?

Question:

I’m trying to understand why a double bracket list throws an error when using .split().
If I can’t get rid of the double brackets, what are other ways to split both double and single bracket lists?

example :

y = (['3801 - 2', '123 + 49'])
print(type(y))
for i in y:
    print(i.split(' '))

output:

<class 'list'>
['3801', '-', '2']
['123', '+', '49']

While

x = ([['3801 - 2', '123 + 49']])
print(type(x))
for i in x:
    print(i.split(' '))

output:

<class 'list'>
AttributeError: 'list' object has no attribute 'split'
Asked By: Steven Cunningham

||

Answers:

Because then you have a list inside a list.
The iteration unravels only the outermost list, whose only element is another list (that does not support the split method).

You either use a nested loop:

for j in y:
    for i in j:
        i.split()

or access the first element:

for i in y[0]:
    i.split()
Answered By: norok2

the split method is for string

In the first case you loop in the list and split the string inside

In the second case you loop in the list that contain another list so you try to split that list and not the string inside. And that’s a mistake because list can’t be split.

A list is already splitted 🙂

Answered By: Honorable con
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.