Python map object is not subscriptable [duplicate] - python

This question already has answers here:
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 6 months ago.
Why does the following script give the error:
payIntList[i] = payIntList[i] + 1000
TypeError: 'map' object is not subscriptable
payList = []
numElements = 0
while True:
payValue = raw_input("Enter the pay amount: ")
numElements = numElements + 1
payList.append(payValue)
choice = raw_input("Do you wish to continue(y/n)?")
if choice == 'n' or choice == 'N':
break
payIntList = map(int,payList)
for i in range(numElements):
payIntList[i] = payIntList[i] + 1000
print payIntList[i]

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)

map() doesn't return a list, it returns a map object.
You need to call list(map) if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.
Also, you can do if choice.lower() == 'n': so you don't have to do it twice.
Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.

Don't need to use range for this problem in pypy3 or python3, so it is actually less code..
for i in payIntList: print ( i + 1000 )
and coincidentally matches RustyTom's comment in PhiHag's solution above. Note : Can not reference a map using array brackets [] in pypy3 or python3 or it will throw the same error.
payIntList[i]
Map ref caused the error.

Related

Use two numbers from a list to do simple calculations in Python [duplicate]

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 2 months ago.
I just started my journey into programming with Python and after I finished traversy's crash course video I started doing some small programs to get better at it, but I ran into a problem.
Let's say you ask the user to input a simple math computation, it looks like this and you want to do the addition in this case:
x = ['1','+','2','-','3']
Then I wanted to do a for loop that scans for the + and adds the number before and after the + symbol. But when it prints the supposed result it just prints the entire list.
for i in x:
if i == "+":
add_sum = float(calc_List[i-1]) + float(calc_List[i+1])
print(add_sum)
And I get this message in the terminal when I run it:
add_sum = float(x[i-1]) + float(x[i+1])
~^~
TypeError: unsupported operand type(s) for -: 'str' and 'int'
It seems I can't write it like this, but how can I choose the previous and next number from i in a list and then do any kind of calculation?
I tried to keep the i count into a separate variable like this:
position = 0
for i in x:
position += 1
if i == '+':
a = position - 1
b = position + 1
add_sum = float(x[a]) + float(x[b])
But all I got was this error:
add_sum = float(x[a]) + float(x[b])
^^^^^^^^^^^
ValueError: could not convert string to float: '+'
You need to find the index of i within x and then find the before and after value in the list. This can be achieved like this:
x = ['1', '+', '2', '-', '3']
for i in x:
if i == "+":
add_sum = float(x[x.index(i)-1]) + float(x[x.index(i)+1])
print(add_sum)
This outputs:
3.0
Hope this helps.
using eval()
Code:-
x = ['1','+','2','-','3']
y="".join(x)
print(eval(y))
Output:-
0
2nd method:- This will work on your cases..!
Code:-
x = ['1','+','2','-','3']
check=0
for i in x:
if i=="+" or i=="-":
check+=1
for i in range(len(x)+check-1): #Assuming The sign (+,-) where present has previous and forward numbers
if x[i]=="+":
temp1=int(x[i-1])+int(x[i+1])
x.insert(i+2,str(temp1))
if x[i]=="-":
temp2=int(x[i-1])-int(x[i+1])
x.insert(i+2,str(temp2))
#print(x) #values how store in the list
print(x[-1])
Output:-
0

Python for loop range addition [duplicate]

This question already has answers here:
Python:How to make the sum of the values of a while loop store into a variable?
(4 answers)
Closed 4 months ago.
Hello (beginner here),
I am trying to write a script that prints the sum of every even numbers in the range [0; 100].
However, I am getting a "TypeError: 'int' object is not iterable".
This is my code:
for i in range(0, 101):
total = 0
if i % 2 == 0:
total = sum(i)
print(total)
My error message:
Traceback (most recent call last):
File "", line 4, in
TypeError: 'int' object is not iterable
I've searched this website and Google to understand what I'm doing wrong, but I cant seem to grasp an answer to my specific code.
Any help would be greatly appreciated.
The problem is with the sum function it is not used in that manner. If you give 1 argument then it should be a list then you can use .append() function but in your use-case you can simply use + i.e., addition.
total = 0
for i in range(0, 101):
if i % 2 == 0:
total += i
print(total)
The sum() function can only sum up an iterable (list, dict, etc.). In your loop, your variable i is seen as a solid number, not a list. If you want to sum up every even number, you need to add i to a list:
list1 = []
for i in range(0, 101):
if i % 2 == 0:
list1.append(i)
total = sum(list1)
print(total)
Here is a better version, if you do not want the output after every single addition:
print(sum([i for i in range(0,101, 2)]))
the answer to your question using sum function can simply be
for i in range(0, 101, 2):
total = 0
total = sum(i, total)
print(total)
Learn more about Python loops here!
Learn Python fundamentals here!

Why do I get index error I try to multiply an element of a list?

I am new to Python and don't really understand how lists differ from arrays. Upon searching, they are defined as dynamic arrays. I am unable to understand why I get IndexError when I try multiplying elements of list like array as in the third last line of code below. What restrictions do I face if I try to manipulate a list like an array? Here I have shared a part of my code.
Thanks in advance :)
import cs50
def main():
credit = cs50.get_string("Number: ")
while(int(credit) < 0):
credit = cs50.get_string("Number: ")
if int(credit) < 1000000000000 or int(credit) > 9999999999999999:
print("INVALID")
quit()
cred = credit.split()
n = len(credit)
cred.pop()
cred.reverse()
i = 0
while i < n:
cred[i] = (int(cred[i]) % 10) + (int(cred[i]) // 10)
i += 2
main()
cred.pop()
It makes the list an empty list if it contains only one element

I'm new to programming and am trying my hand at writing my own reverse function. Not going as planned [duplicate]

This question already has answers here:
How do you reverse the words in a string using python (manually)? [duplicate]
(4 answers)
Closed 5 years ago.
Below is a bit of code which seems to work at the start but populates my holding variable with half while leaving the other have in the list that I'm trying to give list elements from. The last element specifically. I don't know why this is not iterating through the entire flist. Help?
Thanks
Sembor
def reverse(text):
flist = []
holding = ""
for i in str(text):
flist.append(i)
print(flist)
for i in flist:
holding = holding + flist[-1]
del flist[-1]
print(holding)
print(flist)
reverse("JamesBond")
Instead of trying to modify your list while iterating over it. Instead, what you should do, is simply create a new string, and append the letters in the reverse order. You can do this by counting backwards using range:
def reverse(text):
reverse_string = ""
for i in range(len(text) - 1, -1, -1):
reverse_string += text[i]
print(reverse_string)
reverse("JamesBond")
However, the best way to do this in python, is by making use of slicing, in which, you can simply do:
reverse_string = text[::-1]
As this comment says, the problem is that you're modifying the list as you're iterating over it.
Basically, for i in range plist isn't going through all the elements since you making the list shorter as you loop through it. This is what's happening to your list as you're iterating it.
holding plist
d ["J","a","m","e","s","B","o","n","d"]
^
dn ["J","a","m","e","s","B","o","n"]
^
dno ["J","a","m","e","s","B","o"]
^
dnoB ["J","a","m","e","s","B"]
^
dnoBs ["J","a","m","e","s"]
^ #can't loop any further
What you can do instead is something like this
for i in range(len(plist), -1, -1):
holding = holding + plist[i]
Or this
def reverse(text):
return text[::-1]
Or you could use the built in reversed function, like equaio did.
When creating lists from strings you can use list.comprehension:
[i for i in text]
And you could reverse this by using enumerate for instance:
[text[-ind-1] for ind, i in enumerate(text)]
as I understand you want to take the string "JamesBond" and reverse it to "dnoBsemaJ". I am also extremely new to Python. I gave your function a try and came up with the following. It may not be the prettiest but it does reverse the text.
def reverse(_string):
_stringLen = len(_string)
i = _stringLen - 1
_newstring = ""
while i >= 0:
_newstring = _newstring + _string[i]
i -= 1
return _newstring
print reverse("JamesBond")
Prints out : dnoBsemaJ
Splicing can help you unless you do want to write the algorithm to reverse
>>> k = 'JamesBond'
>>> rev_str = k[::-1]
>>> rev_str
'dnoBsemaJ'
>>> type(rev_str)
<type 'str'>

Why do I keep getting this type error?(python)

I understand this may be basic but I have a task of creating two functions for finding mean and median values and them implementing them into a program which will ask for an input of a sequence of numbers. I made both functions separately and tested them, both worked fine I've now put them into the same program and just keep getting a type error telling me to look back at my mean_average(). Can anyone please tell me what I'm doing wrong and how to go about fixing it. I don't see why the mean function worked perfectly using lists before but now it says the oprand type won't work with 'int' and 'list'.
values = []
loopy = 0
#Median
def median_average(*args):
loop = 0
num_order = sorted(args)
length = len(args)
half_length = int((length/2)-1)
half_length_1 = int((length/2))
if length % 2 == 0:
even_averagenf = (num_order[half_length]+num_order[half_length_1])/2
even_average = float(even_averagenf)
loop = 1
if length % 2 != 0:
odd_average = (num_order[int(half_length_1)])
loop = 2
if loop == 2:
return odd_average
if loop == 1:
return even_average
#Mean
def mean_average(*args):
mean = sum(args)/len(args))
return mean
while loopy < 1:
user_v = (input("Please enter your sequence of numbers, stop by typing 'end':"))
if user_v == "end":
print("The median value of your sequence is:", median_average(values))
print("The mean value of your sequence is:", mean_average(values))
loopy = 1
else:
values.append(int(user_v))
Any help is greatly appreciated
You shouldn't unpack the arguments in your functions
def median_average(*args)
def mean_average(*args)
You want to handle the actual list itself
def median_average(args)
def mean_average(args)
This way args is the list of values, so you can call sum and len on it.

Categories