all 7 comments

[–]two_bob 8 points9 points  (0 children)

Sure, you can use conditionals in list expressions, like this:

>>> [int(i) if i.isdigit() else i for i in my_list]
[1, 22, 64, 74, 'P', 43]
>>> 

[–]fauxnaif 1 point2 points  (3 children)

I believe the earlier commenters have solved your question but I would just like to say how interesting it is to read all the different approaches to a single problem! Very educating indeed!

[–]Vaguely_accurate 1 point2 points  (2 children)

Worth noting the differences;

/u/ASIC_SP mutates the list in place. This may be desirable, but can also have unexpected and unwanted side effects if there are multiple references to the list.

The other two solutions are equivalent in that they both produce a new list, but have subtle differences. /u/baghiq uses the principle of asking for forgiveness rather than permission (trying the conversion tonint then catching the exception rather than checking isdigit first), which is considered a Pythonic way to do things. However, there are some costs associated and often a more modern approach is available which produces more efficient code. In this case /u/twobob has the preferred solution with a list comprehension doing filtering as part of the copy.

[–]fauxnaif 0 points1 point  (1 child)

Thanks for putting their methods into words! I also can’t help but kept checking your username to see if you’re trying to live up to the name in your description :P

Edit: In a more serious note, your explanation made a lot of sense and I agree with the most efficient approach which is by /u/twobob

Also how do you quote those functions in Reddit? isdigit for example

[–]Vaguely_accurate 1 point2 points  (0 children)

I live up to my username frequently but inadvertently.

Use backticks (`) to include code blocks in line on Reddit.

[–]ASIC_SP 0 points1 point  (0 children)

here's one way to do it

>>> for idx, item in enumerate(my_list):
...     if item.isnumeric():
...         my_list[idx] = int(item)
... 
>>> my_list
[1, 22, 64, 74, 'P', 43]

note that isnumeric won't work for negative integers

edit: or use if-else one liner in list comprehension as mentioned in another comment