-1

I want to first convert strings of a list to integers and then add 1 to all elements, for example:

mylist = ["0", "1", "2"]
ints = [int(item) for item in mylist]
ints = ints+1
print(ints)

and then I want the output to be:

1, 2, 3

Not sure how I can do this, some help would be appreciated

Authority
  • 5
  • 2
  • If you want to be able to do that sort of thing, you would be better off with a numpy array rather than a list. – alani Dec 02 '21 at 18:24
  • `ints = [int(item)+1 for item in mylist] print(ints)` – sahasrara62 Dec 02 '21 at 18:25
  • @sahasrara62 Yes that's the direct answer to the question as stated (or near enough - in relation to the existing `ints` rather than the original `mylist` it is `ints = [item+1 for item in ints]`) but it's not going to be a convenient or efficient approach if it is going to be needed extensively. – alani Dec 02 '21 at 18:28
  • depend upon usecase. for small case it will be fine, other wise for large cases it won't be – sahasrara62 Dec 02 '21 at 18:29

2 Answers2

0

something like this

mylist = ["0", "1", "2"]
ints = [int(item)+1 for item in mylist]

print(ints)
eshirvana
  • 23,227
  • 3
  • 22
  • 38
0

You can use NumPy to solve this problem

import numpy as np
myList = ["0","1","2"]
myArray = np.array(myList, dtype=int) + 1
print(myArray)
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44