Jerin Joy
Jerin Joy

Reputation: 1

How to create a new list of integers from a parent list containing integers and string?

List=["2","10","15","23","exit"]

# Output required
List_new = [2,10,15,23]

Upvotes: 0

Views: 49

Answers (4)

mxnthng
mxnthng

Reputation: 64

Just do that:

List_new = [int(i) for i in List if i.isnumeric()]

Upvotes: 0

killersnake1901
killersnake1901

Reputation: 1

You can use .isdigit()

List_given =["2","10","15","23","exit"]
def new_list(List_given):
    List_new = []
    for item in list(List_given):
        if item.isdigit():
            List_new.append(item)
    return List_new
new_list(List_given)

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can use isnumeric

>>> List=["2","10","15","23","exit"]
>>> output = [int(i) for i in List if i.isnumeric()]
>>> print(output)
[2, 10, 15, 23]

Upvotes: 0

Nuri Taş
Nuri Taş

Reputation: 3845

Use isnumeric:

[int(item) for item in List if item.isnumeric()]

Upvotes: 3

Related Questions