Python | Count of Matching i, j index elements

Sometimes, while programming, we can have a problem in which we need to check for ith and jth character of each string. We may require to extract count of all strings with similar ith and jth characters. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force method by which this task can be performed. In this, iterate each element of list and check for each string’s ith and jth character and increase the counter in case we find a match.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Count of Matching i, j index elements
# Using loop
  
# initialize list 
test_list = ['geeks', 'beke', 'treat', 'neke']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize i 
i = 1
  
# initialize j 
j = 3 
  
# Count of Matching i, j index elements
# Using loop
count = 0
for ele in test_list:
    if ele[i] == ele[j]:
        count = count + 1
  
# printing result
print("Total Strings with similar ith and jth elements : " + str(count))

chevron_right


Output :



The original list : ['geeks', 'beke', 'treat', 'neke']
Total Strings with similar ith and jth elements : 2

 

Method #2 : Using sum() + generator expression
This is one liner alternative to perform this task. In this, we perform the task of iteration using generator expression and summation using sum().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Count of Matching i, j index elements
# Using sum() + generator expression
  
# initialize list 
test_list = ['geeks', 'beke', 'treat', 'neke']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize i 
i = 1
  
# initialize j 
j = 3 
  
# Count of Matching i, j index elements
# Using sum() + generator expression
res = sum(1 for ele in test_list if ele[i] == ele[j])
  
# printing result
print("Total Strings with similar ith and jth elements : " + str(res))

chevron_right


Output :

The original list : ['geeks', 'beke', 'treat', 'neke']
Total Strings with similar ith and jth elements : 2



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.