+ 1
Please explain how the output of the following python code is 6???
def count(sequence,item): c=0 for item in sequence: c+=1 return(c) print(count(["a","!",1,"a","b","a"],"a"))
8 Answers
+ 3
line 1: define function "count", set parameters "sequence" and "item".
line 2: set variable "c" to the integer 0
line 3: look inside the "sequence" variable, set "item" to be each element that is iterated to
line 4: variable "c" increment by 1
line 5: return the variable "c"
As you can see, as soon as you call the for loop, the parameter "item" is replaced by the element in the sequence as the loop goes through each one. When you call a for loop in that way, what it really asks Python:
For each element in "sequence", set that element as the variable "item".
You can rewrite it as either:
c = 0
for idx in range(len(sequence)):
if sequence[idx] == item:
c += 1
return c
or, a better way:
seq = ["a","!",1,"a","b","a"]
print(seq.count("a"))
+ 8
You are incrementing c for each element of the sequence, returning len(sequence).
This works:
def count(sequence, item):
c=0
for x in sequence:
if x == item:
c+=1
return(c)
print(count(["a","!",1,"a","b","a"],"a"))
You can get the same result with the built-in count method:
print(["a","!",1,"a","b","a"].count("a"))
https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/methods/list/count
+ 1
because the 1 is not a string. look at " "
+ 1
a isn't demand, c will be +1 for every string which is in list. (There's a list in the list)
0
why is the output not 3 because there are exactly 3 "a" in the given list
0
thank you so much @Sapphire and @ Gordie for clearing my doubt,ššš
0
thanks sir