Skip to content Skip to sidebar Skip to footer

What Does Int(n) For N Mean?

In order to put the input into a list: numbersList = [int(n) for n in input('Enter numbers: ').split()] Can someone explain what does 'int(n) for n in' mean? How do I improve th

Solution 1:

The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.

https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

Given your code:

numbersList = [int(n) for n ininput('Enter numbers: ').split()]

Lets say you run the code provided, you get a prompt for input:

Enter numbers:1082533

Now what happens is, Python's input() function returns a string, as documented here:

https://docs.python.org/3/library/functions.html#input

So the code has now essentially become this:

numbersList = [int(n) for n in "10 8 25 33".split()]

Now the split() function returns an array of elements from a string delimited by a given character, as strings.

https://www.pythonforbeginners.com/dictionary/python-split

So now your code becomes:

numbersList = [int(n) for n in ["10", "8", "25", "33"]]

This code is now the equivalent of:

numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
    numberList.append(int(n))

The int(n) method converts the argument n from a string to an int and returns the int.

https://docs.python.org/3/library/functions.html#int

Solution 2:

For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']

int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.

Solution 3:

let us try to understand this list comprehension expression though a simple piece of code which means the same thing.

nums = input('Enter numbers: ') # suppose 5 1 3 6 

nums = nums.split() # it turns it to ['5', '1', '3', '6']

numbersList = [] # this is list in which the expression is writtenfor n in nums: # this will iterate in the nums.
    number = int(n) # number will be converted from '5' to 5
    numbersList.append(number) # add it to the listprint(numbersList) # [5, 1, 3, 6]

Post a Comment for "What Does Int(n) For N Mean?"