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!
Related
This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1
This question already has answers here:
Understanding this Python code from 2014's new year challenge
(6 answers)
Generator expression evaluation with several ... for ... in ... parts
(2 answers)
Explain python list comprehension technique
(2 answers)
Closed 1 year ago.
def sum_five(l):
return sum(num for num in l if num > 5)
#desired outcome:
#sum_five([1, 5, 20, 30, 4, 9, 18]) ➞ 77
#sum_five([1, 2, 3, 4]) ➞ 0
#sum_five([10, 12, 28, 47, 55, 100]) ➞ 252
gotten this as a solution. The question is to loop through a list and sum up those that are less than 5. This is the cleanest and shortest answer which i really loved to learn. Can anyone explain in very simple English to me what does the num for num in l if num > 5 really means?
And give me more examples to understand that logic so i can next time apply it? PS: i can do the outcome using for loop and if statement already, i just want to learn how to use this one liner. Thanks.
This is known as Generator Expression which gives you another list which means like this:
FOR any element which we call it num, in the list which we call it l, if this element(num) is greater than 5, take it and put it in result list.
For example for [1,2,3,4] there is no number greater than 5, so the result is [] which has the summation equal to zero.
Another example is [1,5,20,30,4,9,18] which has the result equal to [20,30,9,18] which has the summation equal to 20+30+9+18 = 77
The list comprehension -- any list comprehension -- can be written as a for loop remembering that it returns a list (meaning you don't have to write the part that assigns the result to a list which in this case I've called out). That's a good thing because that list you are taking the sum of and returning that result instead.
out = []
def sum_five(l):
for num in l:
if num > 5:
out.append(num)
else:
continue
return sum(out)
The general form a list comprehension is worth going into more. But I'm going to strip out some of the code to this for clarity
for num in l:
if num > 5:
num
Goes to this:
for num in l if num > 5:
num
And then to this:
num for num in l if num > 5:
We don't need that colon at the end and the whole thing gets put in braces because that's what specifies a list is getting returned. That leaves us with:
[num for num in l if num > 5]
You then take the sum of that list:
sum([num for num in l if num > 5])
You'll notice the formatting is a bit different than for the loop. If it was just a long no one would use it.
Why should I write this program like this(first way) :
sum = 0
for i in range(1, 10):
if (i % 3 == 0) or (i % 5 == 0):
sum = sum + i
print(sum)
Why cant I write like this?(second way) :
for i in range(1, 10):
if (i % 3 == 0) or (i % 5 == 0):
print(sum(i))
In second way I receive this error :
TypeError: 'int' object is not iterable
What does this error mean exactly?
Where may I use sum function? Where not?
Must I make a list to use sum function?
Thanks a lot
As the doc says, the first argument to the builtin function sum() needs to be an iterable.
Lists and tuples are examples of iterables. An int is not an iterable.
Now, in your first approach, sum is a variable that you have introduced, and unfortunately it has the same name as the built-in function. This should, in general, be avoided (introducing user-defined names that conflict with names of standard functions or modules)
In your second approach, sum refers to the built-in function of that name, and it expects an iterable (eg, list or tuple) as its first argument, but your are passing i, which is an int object
When you wrote sum=0 you have overwritten the python function sum().
so when you write sum(1) you ask python to calculate 0(1) which is not possible since 0 is not iterable
In general, it is not advised to assign sum to a value
What could work is either of the following codes:
s=0
for i in range(1, 10):
if (i % 3 == 0) or (i % 5 == 0):
s+=1
print(s)
or better if you want to use the sum function:
print(sum([i for i in range(10) if (i % 3 == 0) or (i % 5 == 0)]))
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
I've been trying to fix this but the same error message came up every time:
while number_list[i] <= number_list[j]:
IndexError: list index out of range
I've searched for the same type of bug, but not very similar cases found.
Here it is the head program (orders the numbers of my list, from the little one to the bigger):
number_list=[]
list_lenght=int(input("List lenght: "))
while len(number_list)<list_lenght:
item=input("Enter new item to the list:")
number_list.append(item)
print(number_list)
print("That's your number list: ",number_list)
number_list_final=[]
def order_number_list(number_list):
i=0
j=1
while (j)<=(len(number_list)-1):
while number_list[i]<=number_list[j]:
j=j+1
i=j
j=i+1
final_item=number_list[i]
number_list_final.append(final_item)`
del number_list[i]
order_number_list(number_list)
order_number_list(number_list)
print(number_list_final)
I know this is about iterating with the list while modifying it, but no idea how to fix it.
Can anyone help me to debug this, or give me some tips?
Thank you!
number_list=[]
list_lenght=int(input("List length: "))
while len(number_list)<list_lenght:
item=input("Enter new item to the list:")
number_list.append(int(item))
print(number_list)
print("That's your number list: ",number_list)
number_list_final=[]
def order_number_list(number_list):
current_low = ["number"]
current_low[0] = number_list[0]
x = 1
current_low_pos = 0
while x < len(number_list):
if current_low[0] > number_list[x]:
current_low[0] = number_list[x]
current_low_pos = x
x = x + 1
del number_list[current_low_pos]
if number_list == []:
remaining_list = []
else:
remaining_list = order_number_list(number_list)
return (current_low + remaining_list)
number_list_final = order_number_list(number_list)
print(number_list_final)
This is code that has been clarified and corrected.
j was not working right, as other answers have pointed out.
number_list.append(item)
needed to be changed to:
number_list.append(int(item))
because you cant compare strings with the '<' operator.
I also added a return statement, added this line of code:
number_list_final = order_number_list(number_list)
because your final print statement would print an empty list because:
order_number_list(number_list)
doesn't change the variable number_list_final.
I changed some of the function code to simply and make it more readable.
It also explicitly sets the current lowest item to be the first, and changes that if a lower item is found later on.
Hope this helps, let me know if you have any questions!
If I understand you correctly, you're trying to sort a list of numbers. There's a built-in Python method for this, that has been optimized for ages to be fast and use minimal memory, it's called sorted.
Instead of running order_number_list, try:
print(sorted(number_list))
If this is some kind of homework, and you're not allowed to use the built-in sorted, for educational purposes I would recommend you to use a sorting algorithm called bubble sort, more information here - Bubble Sort Homework.
Updating your code to include a couple of print statements shows that the j increases to past the length of the list. Then the "while number_list[i]<=number_list[j]:" no longer can be completed as there is no "number_list[j]" for the j value.
number_list=[1,2,3,4,5]
list_lenght=5
#=int(input("List lenght: "))
#while len(number_list)<list_lenght:
# item=input("Enter new item to the list:")
# number_list.append(item)
# print(number_list)
print("That's your number list: ",number_list)
number_list_final=[]
def order_number_list(number_list):
i=0
j=1
while (j)<=(len(number_list)):
while number_list[i]<=number_list[j]:
print (j)
print (i)
j=j+1
i=j
j=i+1
final_item=number_list[i]
number_list_final.append(final_item)
del number_list[i]
order_number_list(number_list)
order_number_list(number_list)
print(number_list_final)
This outputs :
That's your number list: [1, 2, 3, 4, 5]
1
0
2
0
3
0
4
0
Traceback (most recent call last):
File "C:/Python3/numberlist.py", line 30, in <module>
order_number_list(number_list)
File "C:/Python3/numberlist.py", line 19, in order_number_list
while number_list[i]<=number_list[j]:
IndexError: list index out of range
The code is falling over once j is 5 for this example, it is trying to compare to a number that doesnt exist
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.