Python program to find the character position of Kth word from a list of strings



When it is required to find the character position of ‘K’th word from a list of strings, a list comprehension along with enumerate is used.

Example

Below is a demonstration of the same −

my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) K = 15 print("The value of K is :") print(K) my_result = [element[0] for sub in enumerate(my_list) for element in enumerate(sub[1])] my_result = my_result[K] print("The result is :") print(my_result)

Output

The list is : ['python', 'is', 'fun', 'to', 'learn'] The value of K is : 15 The result is : 2

Explanation

  • A list of strings is defined and is displayed on the console.

  • A value for ‘K’ is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements of the list using enumerate.

  • The zeroth element in every element is accessed using enumerate

  • This is converted to a list.

  • Since enumerate is used, the output would be an integer here.

  • The ‘K’th element of this list is displayed as the output on the console.

Updated on: 2021-09-08T07:19:06+05:30

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements