Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

12.3 Recursion with strings and lists

Learning objectives

By the end of this section you should be able to

  • Demonstrate the use of recursion to solve a string problem.
  • Demonstrate the use of recursion to solve a list problem.
  • Use the built-in count() list function.

Recursion with strings

A word that is spelled the same forward and backward is called a palindrome. Ex: racecar.

Recursion can be used to identify whether a given word is a palindrome.

Recursion with lists

The animation below shows a recursive way to check whether two lists contain the same items but in different order.

The count() function returns a count of the number of items in a list that match the given item, and returns 0 otherwise. Ex: For list_num = [1, 3, 3, 4], list_num.count(3) returns 2.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.