-3

I am trying to get the first (or any) element of a list to integer form.

my_list = ['10','Sally']

I tried:

my_list = map(int, ['10','Sally'][0])

but the output of it is:

<map object at 0x7f3549b8aa58>

How can I fix my code to change it, so that in a one line expression my_list is equal to [10,'Sally']?

v.coder
  • 1,822
  • 2
  • 15
  • 24
PAS
  • 149
  • 1
  • 8

1 Answers1

3

You could do something like this:

[int(x) if x.isdigit() else x for x in my_list]
# [10, 'Sally']

Or maybe (Convert the nth element of a list to integer):

n = 0
[int(v) if i == n else v for i, v in enumerate(my_list)]
# [10, 'Sally']
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • What if `i` is not a string (i.e., doesn't have an `isdigit()` method)? – elethan Dec 23 '16 at 03:04
  • 1
    @elethan Right. There are a lot of assumptions to be made here. A list can contain anything. Without a clearer context, this problem is difficult to touch. – Psidom Dec 23 '16 at 03:09
  • why do you loop through if you only want to change one thing? – PAS Dec 24 '16 at 02:38
  • That is a good point actually. you can just do `my_list[0] = int(my_list[0])` this convert the 0th element to int in place. – Psidom Dec 24 '16 at 03:01