Python List Conversion to string and split


Any Idea when I do the split on list( after converting to string) I am not getting the first and the last elements in the list….

if __name__ =="__main__":
    lst1= ['3 6 2 5'];
    a = [int(i) for i in lst1.split(' ') if i.isdigit()]


[6, 2]

What I am looking for is


I think its due to the split characters which it finds after the 3(first element), but not sure how to resolve it.

Asked By: Faisal Niazi



Try it.

lst1= ['3 6 2 5'];
a = [int(i) for i in lst1[0].split(' ') if i.isdigit()]
Answered By: Leon

When you convert lst1 to a string, you get

"['3 6 2 5']"

When you split this, you get the list: fir

["['3", "6", "2", "5']"]

"['3".isdigit() and "5']".isdigit() are false, so it doesn’t print those elements.

To get the result you expect, you should not convert the list to a string. You should index the list to get its elements.

for s in lst1:
    a = [int(i) for i in s.split(' ') if i.isdigit()]
Answered By: Barmar
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.