Find String in a List using Python



When it is required to find the string in a list, a simple ‘if’ condition along with ‘in’ operator can be used.

Example

Below is a demonstration of the same

Open Compiler
my_list = [4, 3.0, 'python', 'is', 'fun'] print("The list is :") print(my_list) key = 'fun' print("The key is :") print(key) print("The result is :") if key in my_list: print("The key is present in the list") else: print("The key is not present in the list")

Output

The list is :
[4, 3.0, 'python', 'is', 'fun']
The key is :
fun
The result is :
The key is present in the list

Explanation

  • A list of integers and strings is defined and is displayed on the console.
  • A value for key is defined and is displayed on the console.
  • An ‘if’ loop is used to check if the key is present in the list.
  • If yes, the result is displayed on the console.
Updated on: 2021-09-16T08:40:11+05:30

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements