Reverse Lists in Python - python

So I'm trying to create a program in Python that:
A) Prompts a user to enter a number a certain amount of times
B) Then stores those numbers in a list and prints them in reverse order.
This is my code:
for numbers in range (1,4):
print("Please enter a number.")
numbers = input()
numbersList = list(reversed(str(numbers)))
print(numbersList)
When I run it, it just prints <list_reverseiterator object at 0x105447da0>. And even when I tried it without adding 'reversed' in the code, instead of printing a list of ALL the numbers entered in reverse order like I want it to, it spits out the most recent number entered in list format. So if I enter '4' for a number, it just prints: ['4']. No idea why it's doing that. Any help would be appreciated. Thanks.

If I understood correctly, this is what you're looking for:
numbers = []
for i in range (1,4):
print("Please enter a number.")
numbers.append(input())
numbersList = str(numbers)
numbersList.reverse()
print (numbersList)
As commented, i is an iterator generated by range command. One way to collect 3 numbers from the user is to append them into a list, numbers in this case.
After that you can process your list outside the loop. It also seems more viable to reverse the list once it is fully created which again points to outside the loop. I use Python 2.7 so the solution is a bit different than your initial one, but the result is as intended - first it converts all the numbers to strings using map and then it reverses the list in place using reverse.

Try something like this:
numbersList = []
for numbers in range (1,4):
print("Please enter a number.")
numbersList.append(input())
numbersList.reverse()
print(numbersList)
First, you have to define numbersList. Then, you append values to in while in the loop and finally print it out.
Your issue was that you were defining the list each time you ran the for loop (3 times in the above example) and so it only had the last value. (Also, you were tying to print it out each iteration as well).
Also, a 'point of interest' - you can use input("User prompt here: ") to avoid using print() the line before.

l=[]
for _ in range(1,5):
l.append(int(input("enter the number: ")))
print(l[::-1])

Related

How to print the reverse but as a string

I'm working on this question...and have encountered 2 problems that I am not smart enough to solve. Will you help?
Write a program that reads a list of integers, one per line, until an * is read, then outputs those integers in reverse. For simplicity in coding output, follow each integer, including the last one, by a comma.
Note: Use a while loop to output the integers. DO NOT use reverse() or reversed().
my code
user_input = int(input())
my_list = []
while True:
if user_input >= 0:
my_list.append(user_input)
user_input = int(input())
elif user_input <= 0:
print(my_list[::-1])
break
I need to stop when it hits the * but I don't know how to identify that in the code so for testing I set it to print when a negative number is entered.
I need to print the result in reverse without using reverse() but it has to be printed as a string and not a list. Can't figure out how to do that.
Check whether the input is * before converting it to an integer.
my_list = []
while True:
user_input = input('Enter a number, or * to stop')
if user_input = '*':
break
my_list.append(int(user_input))
while len(my_list) > 0:
print(my_list.pop(), end=",") # remove the last element and print it
print()
So, let's break down the the assignment:
Write a program that reads a list of integers, one per line
This means that you should have a loop that reads in values, converts them into an integer and adds them to a list.
But:
until an * is read
This means that you first have to check that the user's input was equal to "*". But, you'll have to be careful to not try to convert the user's input into an integer before you check if it's an asterisk, otherwise an error will be thrown. So, your loop would look like the following:
Get the user's input
Check if it's an asterisk. If so, break the loop.
If the user's input is not an asterisk, convert it to an int, and then add it to your list of inputted integers.
That's all you need for your first loop.
For the second loop, let's refer to the assignment:
then outputs those integers in reverse
This means that you will need a second loop; a for loop would work - you can have the loop go over a range(), except counting backwards. Here is a post about this exact thing.
Your range would start at the length of your list, minus one, because the last index of the list is one less than the number of items, since list indices start at zero.
Then, you end the range at -1, meaning the range will go down to zero, and stop, because it stops before it gets to the specified end.
Your range will count down by -1, instead of the implicit +1 by default. Refer to that post I linked if you're not sure how to do this.
Lastly, we need to actually print the items at those indices.
follow each integer, including the last one, by a comma.
To me this means that either we could output one integer per line, with a comma at the end of each line, or we could print them all in one line, separated by commas.
If you want everything to print on one line, you can just do a regular print() of the item at the current index, followed by a comma, like print(my_list[a] + ',').
But, if you want to output them on separate lines, you can set the end argument of print() to be a comma. This post explains this.
And that's it!
There are other ways to go about this, but that should be a pretty straightforward and clear way to do it.
You can check if the user input equals a string with str(user_input) == '*'.
To print it off in reverse, you could print off the last value of the string repeatedly with print(my_list[:-1]) or use my_list.pop() to take and remove the last value.
I would change around your current code to:
my_list = []
while True:
user_input = int(input())
if str(user_input) == '*':
for num in my_list:
print(my_list.pop())
break
else
my_list.append(int(user_input))

Trying to create a loop in python that gets the user to input the length of the array index

I'm really new to Python, and I'm trying to write a python program that asks the user how many pieces of data they have, and then the user inputs that data which goes into an array. The problem I'm running into is that I must define the length of the array for the program to work, but I want the user to define that as "x". That way, the user can put a specific amount of data into the array.
Here's what I have
i = 0
x = int(input("How many iterations"))
odds = [] #This is where I do not know how to define the array as whatever amount of pieces of data the user wants.
while i < x:
odds[i] = input("Enter number ")
i = i+1
The error message says
IndexError: list assignment index out of range
I'm pretty new to programming, so any help would be much appreciated. I totally understand that I may be going about this problem TOTALLY the wrong way, so please let me know how you would do it. Thanks!
odds is empty so odds[i] is not going to work. try odds.append(input("...")) instead, which will append the new element to the end of odds
In the command
odds[i] = input("Enter number ")
you wanted to change the i-th member of the odds list - but such member yet doesn't exist.
Use
odds.append(input("Enter number "))
instead.
Note: And, instead of the construction
while i < x:
...
i = i + 1
you may use more Pythonic way
for __ in range(x):
...
without the need of using the variable i. (__ - two underline characters - is a correct Python name used for for never used variables).
So your full code will change to
x = int(input("How many iterations: "))
odds = []
for __ in range(x):
odds.append(input("Enter number: ")) # Note: you will append strings, not numbers
The script tries to reference an entry in the list that doesn't exist. Use append to append. Also you don't need a while loop for this. Corrected code:
x = int(input("How many iterations"))
odds =[]
for i in range(x):
odds.append(float(input("Enter number: ")))

How to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop) in python .

I am trying to create a list with multiple datatypes (characters as well as integers) using loop (both for and while loop).
The code snippet using while loop is as follows:-
my_list=[]
item=0
while item!=5:
item=int(input("""Enter the number to create the list(To discontinue enter 5): """))
my_list.append(item)
print("The list created is: ",my_list)
length=len(my_list)
Code snippet using for loop:-
list=[]
#Creating the list
count=int(input("Set the length of list as 7, Enter 7: "))
for i in range(count):
item=int(input("Enter the element: "))
list.append(item)
if (count-i==2):
last_item=int(input("Enter the 7th element:"))
list.append(last_item)
break
print("\nThe list created is: ",list)
My code can create list either with integer or string only. I am unable to mix the datatype(i.e. both integer and string in same list).
Please suggest what modification is needed to be done in my code.
Also, I want to know one more thing,that using while loop we can discontinue the execution.How it can be done when there are multiple datatype elements in list.
my_list=[]
item=0
while item!="5":
item=raw_input("""Enter the number to create the list(To discontinue enter 5): """)
if item.isdigit():
my_list.append(int(item))
else:
my_list.append(item)
print("The list created is: ",my_list)

How do I use variables in a loop with range()? (Python)

I've been searching for quite a while, and I can't seem to find the answer to this. I want to know if you can use variables when using the range() function. For example, I can't get this to work:
l=raw_input('Enter Length.')
#Let's say I enter 9.
l=9
for i in range (0,l):
#Do something (like append to a list)
Python tells me I cannot use variables when using the range function. Can anybody help me?
Since the user inputs is a string and you need integer values to define the range, you can typecast the input to be a integer value using int method.
>> l=int(raw_input('Enter Length: ')) # python 3: int(input('Enter Length: '))
>> for i in range (0,l):
>> #Do something (like append to a list)
You ask user to input a number
l = raw_input('Enter Length: ')
But the problem is that entered number will be presented as a string instead of int. So you have to convert string 2 int
l = int(raw_input('Enter Length: '))
If you use Python 2.X you also can optimize your code - instead of range you might use xrange. It works much faster.
for i in xrange (l):
#Do something (like append to a list)
In Python 3.X xrange was implemented by default
Try this code:
x = int(input("the number you want"))
for i in range(x):

Taking multiple integers on the same line as input from the user in python

I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = []
for i in xrange(1, 10):
num.append(raw_input('Enter the %s number: '))
print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
a, b, c = input().split() # for space-separated inputs
a, b, c = input().split(",") # for comma-separated inputs
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
list(map(inputType, input("Enter").split(",")))
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second)
print('The product of the two is ' + str(product))
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.
I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
Split function will split the input data according to whitespace.
data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = []
# endless loop, exit condition within
while True:
inputstr = input('Enter another string, or nothing to quit: ')
if inputstr:
strings.append(inputstr)
else:
break
This is Python 3 code; for Python 2, you would use raw_input instead of input.
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines:
strings = [line.rstrip('\n') for line in lines]
n = int(input())
for i in range(n):
i = int(input())
If you dont want to use lists, check out this code
There are 2 methods which can be used:
This method is using list comprehension as shown below:
x, y = [int(x) for x in input("Enter two numbers: ").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.
x, y = [int(x) for x in input("Enter two numbers: ").split(",")] # This one is used when you want to input number using comma.
Another method is used if you want to get inputs as a list as shown below:
x, y = list(map(int, input("Enter the numbers: ").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list
Try this:
print ("Enter the Five Numbers with Comma")
k=[x for x in input("Enter Number:").split(',')]
for l in k:
print (l)
How about making the input a list. Then you may use standard list operations.
a=list(input("Enter the numbers"))
# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( )
#for printing
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)
#for multiple inputs
#using list, map
#split seperates values by ( )single space in this case
x=list(map(int,input("enter the numbers: ").split( )))
#we will get list of our desired elements
print("print list: ",x)
hope you got your answer :)

Categories