Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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'

>Solution :

Because when you have a list inside a list.
The iteration unravel only the outermost list, whose only element is another 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading