简体   繁体   中英

How to print specific elements of a list in Python?

I am trying to print the nth value of a list, in this case an integer. However every time I get the entire list as output:

[1, 2, 3]

from this code:

numbers1 = []
numbers1.insert(0, list(map(int, input().split(" "))))


print(numbers1[0])

What am I doing wrong here?

I don't understand why it isn't printing the first element, numbers1[0].

You're inserting a list onto a list so your list actually looks like this:

[ [1, 2, 3] ]

What you want can be accomplished by doing:

numbers1 = list(map(int, input().split(" ")))

or

numbers1.extend(list(map(int, input().split(" "))))

However, I would advise against using map with input in this case because it obfuscates your input and you don't usually want to do that. Instead, try this:

userInput = input()
numbers1.extend( [int(s) for s in userInput.split(" ")] )

This code does the same thing but as a list comprehension, which avoids the call to map and the call to list , reducing overhead while improving readability. This is also more Pythonic IMHO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM