1

So lets say for example I had a list

list1 = ["George", "47", "62", "71", "Apples"] 

Is there a way I could do something like list2 = list1[1:4] and convert all of those values to integers at the same time, or at least right after.

EDIT: What I just now implemented was right after the assignment of it (so in this case right after list2 = list1[1:4]) I did a for loop that was formatted as the following

for i in range(len(list2) :
   list2[i] = int(list2[i])

I feel this isn't the most elegant way to do this, so I still would appreciate any input, as I have multiple lists I need to do this to so doing it this way multiple times feels... sloppy to say the least.

Mr. T
  • 8,325
  • 9
  • 23
  • 44

2 Answers2

0

I think you're looking for map().

For example:

>>> list(map(int,['01','02','03']))
[1, 2, 3]
user1104372
  • 128
  • 5
0

The answer depends on how foolproof you want to make it. The easiest way is the mapping suggested by user1104372. You could also use a list comprehension.

list1 = ["George", "47", "62", "71", "Apples"] 
list2 = [int(i) for i in list1[1:4]]
>>>[47, 62, 71]

This will not work if you had a mixed list, so we have to check if the string is an integer representation:

list1 = ["George", "47", "62.3", "Bahamas", "71", "Apples"] 
list2 = [int(i) for i in list1[1:5] if i.isnumeric()]
>>>[47, 71]

Unfortunately, this excludes negative numbers. We could use regex for more complicated parsing tasks like that:

import re
list1 = ["George", "+47", "62.3", "Bahamas", "-71", "Apples"] 
list2 = [int(i) for i in list1[1:5] if re.match("[-+]?\d+$", i)]
>>>[47, -71]

The latter could be extended to more complicated cases like "39.000" which is a representation of an integer - but this goes beyond the scope of your question.

Mr. T
  • 8,325
  • 9
  • 23
  • 44
  • 1
    Thanks a lot! This is way more information that I asked for but in a totally good way. I appreciate it! – BolognaBruh Nov 18 '20 at 16:11
  • Glad to be of help. This `range(len(list2)` was my preferred style when I started with Python until I noticed that you should use either directly `for egg in eggbasket:` or, if you really need the index (which you rarely do) `for i, egg in enumerate(eggbasket):`. This makes life so much easier. – Mr. T Nov 18 '20 at 16:24