Python Forum
Occurrences using FOR and IF cycle
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Occurrences using FOR and IF cycle
#2
1. Don't use range(len(a)), python cycle iterates over values, not indexes, just write
for item in a:
2. Your code works well
a = [100, 100, 50, 20, 100, 30]
x = 100
c = 0
for i in range(len(a)):
    if x == a[i]:
        c = c + 1

print(c)
>>> 3
3. Better code
a = [100, 100, 50, 20, 100, 30]
x = 100
c = sum(1 for i in a if i == x)

print(c)
Reply


Messages In This Thread
Occurrences using FOR and IF cycle - by P86 - Jul-29-2019, 01:11 PM
RE: Occurrences using FOR and IF cycle - by fishhook - Jul-29-2019, 01:21 PM
RE: Occurrences using FOR and IF cycle - by ThomasL - Jul-29-2019, 04:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing a cycle to find the nearest point from the array Tysrusko 0 173 May-10-2024, 11:49 AM
Last Post: Tysrusko
  Need to fix SyntaxError in cycle try alexfrol86 14 3,277 Mar-27-2022, 07:53 AM
Last Post: stevendaprano
  Count number of occurrences of list items in list of tuples t4keheart 1 2,415 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Trying to cycle through a list of charcters pooky2483 12 4,583 Sep-28-2020, 06:55 AM
Last Post: pooky2483
  Count & Sort occurrences of text in a file oradba4u 7 3,147 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  <while> cycle is not interrupted when using the <random>module ShityCoder 3 2,231 Sep-04-2020, 04:05 PM
Last Post: ShityCoder
  Cycle of numpy variables Zero01 0 1,578 Jul-31-2020, 11:58 AM
Last Post: Zero01
  stop cycle while windows11 1 2,064 May-16-2020, 03:17 PM
Last Post: deanhystad
  Counting number of occurrences of a single digit in a list python_newbie09 12 5,662 Aug-12-2019, 01:31 PM
Last Post: perfringo
  pool map cycle skorost5 5 3,877 Apr-07-2019, 09:21 AM
Last Post: skorost5

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020