0

How would one answer this foor loop question using proper python syntax:

def int_all_2(str_list):
    '''(list of str) -> NoneType
    Replace every str element of str_list with its corresponding
    int version.
    For example,
    >>> sl = ['100', '222', '2', '34']
    >>> int_all_2(sl)
    >>> sl
    [100, 222, 2, 34]
    '''

Would it be like this?

l = []
  for x in str_list:
    l.append (int_all_2(x))
    return l
2
  • 1
    Please format the code properly. Also, if you have a possible solution already then could you not just try if it works? Commented Oct 9, 2015 at 19:47
  • Assuming your list ONLY contains numeric integer strings: l = [int(itm) for itm in str_list] Commented Oct 9, 2015 at 21:31

2 Answers 2

1

If you want to convert each element of the list to integer and then return a new list you can use map function :

def strs2ints(l):
   return map(int,l)

You should also note that function strs2ints doesn't change the contents of array l.

In case you want to change the contents of the original array l, which I do not recommend(you should prefer using "clean" functions over functions with side-effects) you can try the following code :

def strs2ints(l):
    for i in range(len(l)):
       l[i] = int(l[i])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much it makes perfect sense now!
0

Assuming your list contains only string representation of numeric integers, you don't even need a function, just list comprehension:

l = [int(itm) for itm in str_list]

If you want to ignore possible strings:

l = [int(itm) for itm in str_list if not itm.isalpha]

Or, if you require a function:

def int_all(str_list):
    return [int(itm) for itm in str_list]

Comments

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.