Andros Adrianopolos
Andros Adrianopolos

Reputation: 674

How to convert a list of strings to a list of ints in Python 3x

I'm trying to convert a list of numbers in string format to integers.

I've tried list comprehension: marks = [int(x) for x in marks] and I've also tried mapping: new_list = list(map(int, marks)) but both of them lead to a TypeError:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Full code:

size = int(input())
students_and_marks = []
students = []
marks = []

for x in range((size * 2)):
    students_and_marks.append(input())

for x in range(1):
    students.append(students_and_marks[0::2])
    marks.append(students_and_marks[1::2])

new_list = list(map(int, marks))

Upvotes: 2

Views: 74

Answers (2)

hygull
hygull

Reputation: 8740

Replace both append() method in 2nd loop with extend() and you are done.

Note: The strategy that you are following is good if you are a beginner otherwise there exists best ways to do the same in a simple and with less code (time/space efficient).

Finally, your code will look like:

size = int(input())
students_and_marks = []
students = []
marks = []

for x in range((size * 2)):
    students_and_marks.append(input())

print(students_and_marks)
for x in range(1):
    students.extend(students_and_marks[0::2])
    marks.extend(students_and_marks[1::2])

print(marks)                     # ['R A', '2', 'K T', '4', 'P K', '6']
new_list = list(map(int, marks)) # ['2', '4', '6']
print(new_list)                  # [2, 4, 6]

Terminal input & output

Rishikeshs-MacBook-Air:PythonCode hygull$ python3 stk_prob_str.py 
3
R A
2
K T
4
P K
6
['R A', '2', 'K T', '4', 'P K', '6']
['2', '4', '6']
[2, 4, 6]

Upvotes: 0

Skam
Skam

Reputation: 7798

Both your code samples are correct. If you want to apply a function to a list you can either use a list comprehension or a pass a map to the list constructor though the list comprehension is preferred.

The issue is with the input. Specifically,

marks.append(students_and_marks[1::2])

Consider,

>>> a = [1,2,3,4,5]
>>> a[1::2]
[2, 4]

From your question it's not clear what you intended to do with your slice i.e. students_and_marks[1::2]. You append it to marks even though students_and_marks[1::2] is already a list.

What you did was,

>>> marks = ['1', '2']
>>> nested_marks = []
>>> nested_marks.append(marks)
>>> nested_marks
[['10', '9']]
>>> int(nested_marks)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

While I believe you intended to do,

>>> students_and_marks = ['Linus', '10', 'David', '9']
>>> students = students_and_marks[::2]
>>> students
['Linus', 'David']
>>> marks = students_and_marks[1::2]
>>> marks
['10', '9']
>>> new_marks = [int(mark) for mark in marks]
>>> new_marks
[10, 9]

Upvotes: 2

Related Questions