0

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'];
    lst1=str(lst1);
    a = [int(i) for i in lst1.split(' ') if i.isdigit()]
    print(a);

Outputs

[6, 2]

What I am looking for is

[2,3,5,6]

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

5
  • Print str(lst1) to see what the problem is. Commented Jan 26, 2023 at 20:10
  • Probably you want lst1[0] instead. Commented Jan 26, 2023 at 20:11
  • Print lst1 returns ['3 6 2 5'] which is the original list Commented Jan 26, 2023 at 20:15
  • 1
    Why are you converting lst1 to a string in the first place? It contains a string as the element, use that. Commented Jan 26, 2023 at 20:20
  • 1
    i understand. its part of something i am trying to do .. a lot going on afterward... Commented Jan 26, 2023 at 20:23

2 Answers 2

2

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()]
    print(a)
Sign up to request clarification or add additional context in comments.

Comments

0

Try it.

lst1= ['3 6 2 5'];
a = [int(i) for i in lst1[0].split(' ') if i.isdigit()]
a.sort()
print(a)

1 Comment

yeap,, this worked... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.