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'
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()
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 🙂
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'
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()
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 🙂