How to add a list of str + int using list comprehension?

Viewed 70

Ok, first of all, I'm a total newb in python. So, what I'm trying to achieve is creating a list of lists, in which first element is a string and second is an integer. First, I enter a number of sets and then every set on a new line, so it looks like this:

3
Alex 40
Boris 30
Claire 50

This seems to be working

n = int(input())
nums = []
for i in range(n):
    num = input().split()
    num[1] = int(num[1])
    nums.append(num)

But I've been trying to improve this method:

n = int(input())
nums = []
for i in range(n):
    nums.append([[x, int(y)] for x, y in input().split()])

Which in return gives me "ValueError: too many values to unpack (expected 2)"

2 Answers

That's what input().split() is doing under-the-hood:

input().split()
"Boris 30".split()
["Boris", "30"]

Every time you iterate over ["Boris", "30"], it'll yield first "Boris" and then "30". So when you do

[... for x, y in input().split()]

What you're actually doing is:

[... for x, y in ["Boris", "30"]]

At first it may look it's doing the right thing, but it's trying to unpack the string "Boris" into x and y (thus the "too many values to unpack" error: it expected only 2 values, but it received 5). Note that if "Boris" was replaced with "Bo", the code would not raise this specific error (but it still wouldn't do what you're expecting).

You can fix this by unpacking the input().split() itself:

n = int(input())
nums = []
for i in range(n):
    x, y = input().split()
    nums.append([x, int(y)])

Split the user input into a list, and remove the unnecessary list comprehension. Also, provide meaningful messages to the user:

n = int(input('enter the number of lines: '))
nums = []
for i in range(n):
    lst = input('enter name and age: ').split()
    nums.append([lst[0], int(lst[1])])
print(nums)
Related