Adding Numbers to a list using variable - python

I'm doing a programming question and I need a bit of help.
I have a variable where I type in a number and then that number and all the numbers before it go in a list.
For example:
I pick 10 and put it in a variable
And all numbers from 1 - 10 are put in a list
Here is my code:
Top_Num = int(input('Top Number'))
Nums = []
Now lets say I chose 10 for the Top_Num, how do I put 10 numbers into the list?
Thanks.

You can actually use Pythons built in range(int) function to do exactly this.
If you want the array to start at 1 and include the input number, you can use
Nums = list(range(1, Top_Num + 1))
The first argument of 1 indicates the start value of the array, and the second argument Top_Num + 1 is the number that the array goes up to (exclusive).

Nums = [num for num in range(1, Top_Num + 1)]
It uses list comprehensions too, which is (kinda) an important concept in python.

Related

How to assemble nested-list elements

def nested_list(nested):
for i in range (0, len(nested)):
for k in range (0, len(nested)):
print(nested[i][k], end = " ")
nested_list([[1,2,3],[4,5,6],[7,8,9]])
output : 1 2 3 4 5 6 7 8 9
İt is working.
But when I change nested_list([[1,2,3,4],[5,6],[7,8,9,10]])like this I get an error. What is the best solution to fix this problem ?
You get an error because your original code assumes "square" list (sublists of the same length like full list).
You need to change inner for loop to check for len of current sublist, not whole list:
def nested_list(nested):
for i in range(len(nested)):
for k in range(len(nested[i])): # check len of current sublist
print(nested[i][k], end = " ")
Also changed range(0, len(nested)) to just range(len(nested)). Range works both as range(start, stop[, step]) (if no step is given, 1 is the default) and range(stop) which starts from 0. :)
range signatures in builtin functions list, real description of how range works
There is a fast way to do this:
nested_list = [[1,2,3],[4,5,6],[7,8,9]]
print(sum(nested_list, []))
The sum Python's built-in function can be used to "sum" (and in this case to concatenate) the elements in an iterable.

Python 3: Executing a For loop x number of times by using a variable

Edit: Fixed the screwed up brackets, sorry. Should have caught this. Let's see if this clarifies what I'm trying to do.
I want to do a basic program that takes the variable "run" and runs the following code that number of times by using a For loop.
run = 3
def program(run):
for i in range(5):
print("The number is",i)
program(run)
What I want is to get is:
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
i.e. the "program" loops however many times I set "run" to equal.
Let's break the code and the error message down a bit:
for i in range[5]:
TypeError: 'type' object is not subscriptable
"Subscripting" is the way you access a particular element in a container, like a list or a dict. For example, to get the first (0th) element of a list called foo, you'd say foo[0], and to get the value associated with the key "bar" in a dictionary called foo, you'd say foo["bar"].
Note that when you just use the [] symbols by themselves (instead of putting them after some other identifier), they serve a different purpose: they construct a list. The expression [5] is a list that contains a single element (the number 5). To represent more elements, you comma-separate them, e.g. [0, 1, 2, 3, 4].
So what the error is telling you is that a type object can't be subscripted. Does that mean that range is a type? Yes! In Python, a range is a type of iterable object that represents a range of numbers. On its own, the word range in a Python program refers to the entire class of range objects (that is, a type of object), not a particular range object.
You construct a range the same way you construct most objects, by calling the type as a constructor function, with parameters in parentheses. For example, to construct a range with 5 numbers in it (0 to 4, similar to the list [0, 1, 2, 3, 4]) you can simply say range(5).
So to print all the numbers from 0 to 4 you can do:
for i in range(5):
print("The number is", i)
In your code, the run variable serves no purpose and can be removed completely.
Functions can take any number of parameters, or none at all, and since in this case your function doesn't do anything with the parameter you pass in, it can be simply:
def program():
for i in range(5):
print("The number is", i)
program()
If you wanted to make the length of the range variable, that would make sense as a parameter -- you just need to pass the parameter along to your range construction:
def program(num):
for i in range(num):
print("The number is", i)
runs = 3
for _ in range(runs):
program(5)
You'd use range, but you would use parenthesis to call the function instead of braces. I.e. range(5) instead of range[5]. Or you could use your run variable like range(run)
In short you are seeing the error because you are using square brackets and not parentheses range() is a function. Change it to
def program(run):
for i in range(5):
print("The number is",i)
program(run)
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
and it works fine.
If you want to the program to loop the same number of times as specified in run then you can do this:
run = 5
def program(run):
for i in range(run):
print("the number is",i)
program(run)
def program(n):
for i in range(0,n+1):
print("The number is",i)
program(5)
ouput
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Give this a try. Hopefully understood the assignment:
run = 3
def program(run):
nums = [f'The number is: {n}' for r in range(run) for n in range(5)]
print('\n'.join(nums))
program(run)
This uses list comprehension to loop twice which translates to:
run = 3
def program(run):
for r in range(run):
for n in range(5):
print(f'The number is: {n}')
program(run)
Or:
run = 3
def program():
for n in range(5):
print(f'The number is: {n}')
for r in range(run):
program()
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
Whelp, I finally figured it out - the reason I couldn't seem to find a solution anywhere to "could this be done and how would I go about it" is that in Python at least, a For statement cannot do this kind of loop, only a While can.
So my experiment of trying to do this via a For is a moot point, it's not something that can be coded without using While.
Thanks for the help.

How to add values into an empty list from a for loop in python?

The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]

How to strip white spaces in Python without using a string method?

I am fairly new to programming and have been learning some of the material through HackerRank. However, there is this one objective or challenge that I am currently stuck on. I've tried several things but still cannot figure out what exactly I am doing wrong.
Objective: Read N and output the numbers between 0 and N without any white spaces or using a string method.
N = int(input())
listofnum = []
for i in range(1, N +1):
listofnum.append(i)
print (*(listofnum))
Output :
1 2 3
N = int(input())
answer = ''
for i in range(1, N + 1):
answer += str(i)
print(answer)
This is the closest I can think of to 'not using any string methods', although technically it is using str.__new__/__init__/__add__ in the background or some equivalent. I certainly think it fits the requirements of the question better than using ''.join.
Without using any string method, just using integer division and list to reverse the digits, print them using sys.stdout.write:
import sys
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
sys.stdout.write(chr(c+48))
Or as tdelaney suggested, an even more hard-code method:
import os,sys,struct
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
os.write(sys.stdout.fileno(), struct.pack('b', c+48))
All of this is great fun, but the best way, though, would be with a one-liner with a generator comprehension to do that, using str.join() and str construction:
"".join(str(x) for x in range(1,N+1))
Each number is converted into string, and the join operator just concatenates all the digits with empty separator.
You can print numbers inside the loop. Just use end keyword in print:
print(i, end="")
Try ''.join([str(i) for i in range(N)])
One way to accomplish this is to append the numbers to a blank string.
out = ''
for i in range(N):
out += str(i)
print(out)
You can make use of print()'s sep argument to "bind" each number together from a list comprehension:
>>> print(*[el for el in range(0, int(input())+1)], sep="")
10
012345678910
>>>
You have to do a simple math to do this. What they expect to do is multiply each of your list elements by powers of ten and add them up on each other. As an example let's say you have an array;
a = [2,3,5]
and you need to output;
235
Then you multiply each of loop elements starting from right to left by 10^0, 10^1 and 10^2. You this code after you make the string list.
a = map(int,a)
for i in range(len(a)):
sum += (10**i)*a[-i]
print sum
You are done!

Index error:list assignment index out of range

I want to:
Take two inputs as integers separated by a space (but in string form).
Club them using A + B.
Convert this A + B to integer using int().
Store this integer value in list C.
My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a is going out of the range (it must be starting from 0 ending at 3)?
Why it is showing this error?
Why your error is occurring:
You can only reference an index of a list if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change the index 0, which does not exist as the list is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.
The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices
Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]

Categories