Reputation: 37
I am trying to make a function that takes in a list as an input parameter. I am to use a while loop to iterate over the list and keep track of the amount of integers and strings that are included in the list. This is what i have so far:
def usingwhileloop(mylist):
count = 0
int_total = 0
str_total = 0
while count <= len(mylist):
if isinstance(mylist[count], int) == True:
int_total = int_total + 1
elif isinstance((mylist[count]), str) == True:
str_total = str_total + 1
count = count + 1
newlist = [int_total, str_total]
return newlist
When I run for a list like [1, 2, 3, “a”, “b”, 4] it should return [4, 2] but instead i get the following error: "line 51, in usingwhileloop if isinstance(what[count], int) == True: IndexError: list index out of range"
what am i doing wrong? I struggle with while loops...
Upvotes: 2
Views: 63
Reputation: 5062
If you really require a while loop then see the answer by josephting.
For the example that you have shown though, you don't need a while
loop, e.g.
"""
Some simple functions
"""
def count_types_ex1(items):
"""Count types from a list"""
counters = [0, 0]
for item in items:
if isinstance(item, int):
counters[0] += 1
elif isinstance(item, str):
counters[1] += 1
return counters
print(count_types_ex1([1, 2, 3, 'a', 'b', 4]))
def count_types_ex2(items):
"""Count types from a list"""
check_type = lambda x: [int(isinstance(x, int)), int(isinstance(x, str))]
counters = [check_type(x) for x in items]
return sum(x[0] for x in counters), sum(x[1] for x in counters)
print(count_types_ex2([1, 2, 3, 'a', 'b', 4]))
Output:
[4, 2]
(4, 2)
Upvotes: 1
Reputation: 2665
It's because you were trying to access an item from the list that doesn't exist.
Why? Assuming we're using this list as example - [1, 2, 3, “a”, “b”, 4]
count starts from 0 so I assume you expect count to go from 0 to 5.
0: 1
1: 2
2: 3
3: "a"
4: "b"
5: 4
However, len(mylist)
is 6
so the loop will attempt to access mylist[6]
which does not exist.
You have to modify your while loop to stop at 5 instead. To do that, while count <= len(mylist) - 1:
or while count < len(mylist):
will do.
Upvotes: 1