Python | program to check each string in the list of strings whether it is palindrome or not and showing that result in the list of tuple forms.

Python | program to check each string in the list of strings whether it is palindrome or not and showing that result in the list of tuple forms.

A string is said to be palindrome if the reverse of the string is the same as the string. For example, “naman” is a palindrome, but “ankit” is not a palindrome.

Iterative Method:

  • Run a loop from start to half of the length of the string.
  • Check the first character to the last character of the string and second to second last one and so on…
  • If any character mismatches, the string wouldn’t be a palindrome.

Input : ['naman','ankit','abcdcba','rahul','priya']

Output : [('naman', 'pallindrome'), ('ankit', 'non-pallindrome'), ('abcdcba', 'pallindrome'), ('rahul', 'non-pallindrome'), ('priya', 'non-pallindrome')]

Let’s see the Python code implementation:



# define a function to check string is 
# palindrome or not 
def check_palindrome(name , result):

    c = 0

    # run loop from 0 to len // 2
    # len // 2 gives integer division
    for j in range(0 , len(name) // 2):

        # here we check character by charcter
        if name[j] != name[(len(name) - 1) - j]:

            c = 1
            break

    if c == 0:

        # we use the append method of the list to insert 
        # the tuple at the last index of the list.
        result.append((name , 'pallindrome'))

    else:
        result.append((name , 'non-pallindrome'))


# main code
if __name__ == "__main__" :
  
  # given input list of strings
  name_list = ['naman','ankit','abcdcba','rahul','priya']

  # take empty list 
  result = []

  # perform iteration in the list
  for name in name_list:

      # function call
      # pass two arguments
      check_palindrome(name , result)

  # print the result after coming out of the loop
  print(result)

Output:

[('naman', 'pallindrome'), ('ankit', 'non-pallindrome'), ('abcdcba', 'pallindrome'), ('rahul', 'non-pallindrome'), ('priya', 'non-pallindrome')]

1 Comment

Leave a Reply

Your email address will not be published.

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds