- Get a list of numbers as input from the user
- 11 Answers 11
- Example
- Using Python-like syntax
- Do not ever use eval for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.
- Using your own syntax
- Using other syntaxes
- Verifying input
- Listing numbers in python
- # Table of Contents
- # Create a list of numbers from 1 to N in Python
- # Create a list of numbers from 1 to N using a list comprehension
- # Using a floating-point number for the step with numpy
- # Create a list of numbers from 1 to N using a list comprehension
- # Create a list of numbers from 1 to N using a for loop
- # Create a list of numbers from 1 to N using a while loop
- # Additional Resources
- How can I generate a list of consecutive numbers? [duplicate]
Get a list of numbers as input from the user
the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.
«it seems to interpret the input as if it were a string.» No «interpretation» happens (unless you count translating keystrokes into bytes and then bytes into text); the input is a string.
11 Answers 11
a = [int(x) for x in input().split()]
Example
>>> a = [int(x) for x in input().split()] 3 4 5 >>> a [3, 4, 5] >>>
@StevenVascellaro Yes although the expression would be str(x) instead of string(x) since str is python’s way of saying string
@DhirajBarnwal If you want to know what’s going on there: input() to read input + split() to split the input on spaces + [f(x) for x in iter] to loop over each of those + int to turn each into an int. If you want to know how one can come up with it: it’s mostly just figuring out what you want to do and which pieces you need to put together to achieve that.
It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:
s = input() numbers = list(map(int, s.split()))
s = raw_input() numbers = map(int, s.split())
what if my input is having mixed datatype string and integer then how can i split them and convert to list. input: ‘aaa’ 3 45 554 ‘bbb’ 34 ‘ccc’ i added the contents seperated by space!!
@FarhanPatel That’s an unrelated question, so I suggest asking a new question. Start with looping over s.split() or shlex.split(s) if you want to allow spaces inside quoted strings.
posting it as a new question, thnx for the encouragement, was scary it might not be marked as duplicate!! stackoverflow.com/questions/43822895/…
Using Python-like syntax
The standard library provides ast.literal_eval , which can evaluate certain strings as though they were Python code. This does not create a security risk, but it can still result in crashes and a wide variety of exceptions.
For example: on my machine ast.literal_eval(‘[‘*1000 + ‘]’*1000) will raise MemoryError , even though the input is only two kilobytes of text.
As explained in the documentation:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis .
(The documentation is slightly inaccurate. ast.literal_eval also supports addition and subtraction of numbers — but not any other operators — so that it can support complex numbers.)
This is sufficient for reading and parsing a list of integers formatted like Python code (e.g. if the input is [1, 2, 3] . For example:
>>> import ast >>> ast.literal_eval(input("Give me a list: ")) Give me a list: [1,2,3] [1, 2, 3]
Do not ever use eval for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.
It cannot be properly sandboxed without significant expertise and massive restrictions — at which point it is obviously much easier to just use ast.literal_eval . This is increasingly important in our Web-connected world.
In Python 2.x, raw_input is equivalent to Python 3.x input ; 2.x input() is equivalent to eval(raw_input()) . Python 2.x thus exposed a critical security risk in its built-in, designed-to-be-beginner-friedly functionality, and did so for many years. It also has not been officially supported since Jan 1, 2020. It is approximately as outdated as Windows 7.
Do not use Python 2.x unless you absolutely have to; if you do, do not use the built-in input .
Using your own syntax
Of course, it is clearly possible to parse the input according to custom rules. For example, if we want to read a list of integers, one simple format is to expect the integer values separated by whitespace.
To interpret that, we need to:
All of those tasks are covered by the common linked duplicates; the resulting code is shown in the top answer here.
Using other syntaxes
Rather than inventing a format for the input, we could expect input in some other existing, standard format — such as JSON, CSV etc. The standard library includes tools to parse those two. However, it’s generally not very user-friendly to expect people to type such input by hand at a prompt. Normally this kind of input will be read from a file instead.
Verifying input
ast.literal_eval will also read and parse many things that aren’t a list of integers; so subsequent code that expects a list of integers will still need to verify the input.
Aside from that, if the input isn’t formatted as expected, generally some kind of exception will be thrown. Generally you will want to check for this, in order to repeat the prompt. Please see Asking the user for input until they give a valid response.
Listing numbers in python
Last updated: Feb 22, 2023
Reading time · 5 min
# Table of Contents
# Create a list of numbers from 1 to N in Python
To create a list of numbers from 1 to N:
- Use the range() class to create a range object from 1 to N.
- Use the list() class to convert the range object to a list.
- The new list will contain the numbers in the specified range.
Copied!list_of_numbers = list(range(1, 6)) print(list_of_numbers) # 👉️ [1, 2, 3, 4, 5] list_of_numbers = list(range(1, 10, 2)) print(list_of_numbers) # 👉️ [1, 3, 5, 7, 9]
The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.
Copied!list_of_numbers = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(list_of_numbers)
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1 .
If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.
Copied!list_of_numbers = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(list_of_numbers)
If you need to specify a step, pass a third argument to the range() class.
Copied!list_of_numbers = list(range(1, 10, 2)) print(list_of_numbers) # 👉️ [1, 3, 5, 7, 9]
The list contains every second number starting from 1 to 10 .
The step argument can only be set to an integer.
# Create a list of numbers from 1 to N using a list comprehension
You can also use a list comprehension to create a list of numbers from 1 to N.
Copied!start = 1 stop = 5 step = 0.5 list_of_numbers = [ x * step for x in range(2*start, 2*stop + 1) ] # 👇️ [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0] print(list_of_numbers)
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
The list in the example starts at 1 and goes to 5 (inclusive) in increments of 0.5 .
You can update the start , stop and setup values.
This approach is useful when you have a step value that is not an integer because the range() class only supports integer values.
# Using a floating-point number for the step with numpy
If you need to use a floating-point number for the step , use the numpy.arange() method.
Copied!import numpy as np list_of_numbers = np.arange(1, 10, 0.5).tolist() # 👇️ [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, # 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5] print(list_of_numbers)
The numpy.arange method returns an array of evenly spaced values within the given interval.
We used the tolist method to convert the array to a list.
If you need to install the NumPy package, run the following command.
Copied!pip install numpy # 👇️ or pip3 pip3 install numpy
You can omit the step argument to get a list of values from 1 to N in increments of 1.
Copied!import numpy as np list_of_numbers = np.arange(1, 11).tolist() # 👇️ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list_of_numbers)
The numpy.arange() method is very similar to the range() class but allows for step values that are floating-point numbers.
# Create a list of numbers from 1 to N using a list comprehension
You can also use a list comprehension to create a list of numbers from 1 to N.
Copied!list_of_numbers = [number for number in range(1, 6)] print(list_of_numbers) # 👉️ [1, 2, 3, 4, 5]
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we return the current number.
The new list contains the numbers in the range object.
However, this isn’t necessary unless you need to perform some operation for every number in the range object.
# Create a list of numbers from 1 to N using a for loop
The same can be achieved using a simple for loop.
Copied!list_of_numbers = [] for number in range(1, 6): list_of_numbers.append(number) print(list_of_numbers) # 👉️ [1, 2, 3, 4, 5]
We used a for loop to iterate over the range object.
On each iteration, we use the list.append() method to append the current number to a list.
The list.append() method adds an item to the end of the list.
Copied!my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
Using the list() class to convert the range object to a list should be sufficient unless you have to perform some operation for every number in the range object.
You can also define a reusable function that creates a list of numbers in a for loop.
Copied!def get_range(n): list_of_numbers = [] for number in range(1, n + 1): list_of_numbers.append(number) return list_of_numbers print(get_range(6)) # 👉️ [1, 2, 3, 4, 5, 6] print(get_range(7)) # 👉️ [1, 2, 3, 4, 5, 6, 7]
The function takes n as a parameter and creates a list of numbers from 1 to n.
# Create a list of numbers from 1 to N using a while loop
You can also use a while loop to create a list of numbers from 1 to N.
Copied!def get_range(n): list_of_numbers = [] start = 1 while start n: list_of_numbers.append(start) start += 1 return list_of_numbers print(get_range(6)) # 👉️ [1, 2, 3, 4, 5] print(get_range(7)) # 👉️ [1, 2, 3, 4, 5, 6]
The get_range function takes n as a parameter and creates a list of numbers from 1 to n .
On each iteration, we append the current start value to the list and increment it.
Once the start value is equal to or greater than n , the condition is no longer met and the while loop exits.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How can I generate a list of consecutive numbers? [duplicate]
Note 1: Python 3.x’s range function, returns a range object. If you want a list you need to explicitly convert that to a list, with the list function like I have shown in the answer.
Note 2: We pass number 9 to range function because, range function will generate numbers till the given number but not including the number. So, we give the actual number + 1.
Note 3: There is a small difference in functionality of range in Python 2 and 3. You can read more about that in this answer.
Using Python’s built in range function:
input = 8 output = range(input + 1) print output [0, 1, 2, 3, 4, 5, 6, 7, 8]
input = 8 output = list(range(input + 1)) print(output) [0, 1, 2, 3, 4, 5, 6, 7, 8]
Here is a way to generate n consecutive numbers in equal intervals between them starting from 0 to 100 using numpy:
import numpy as np myList = np.linspace(0, 100, n)
Please don’t post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes
Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.
list = [] calc = 0 while int(calc) < 9: list.append(calc) calc = int(calc) + 1 print list [0, 1, 2, 3, 4, 5, 6, 7, 8]
Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is
x=list(range(10)) #"list"_will_make_all_numbers_generated_by_range_in_a_list #number_in_range_(10)_is_an_option_you_can_change_as_you_want print (x) #Output_is_ [0,1,2,3,4,5,6,7,8,9]
Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !
def consecutive_numbers(n) : list=[i for i in range(n)] return (list) print(consecutive_numbers(10))