Open In App

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

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings.

Examples:

Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 21 
Output : 0
Explanation : 21st index occurs in “geeks” and point to “g” which is 0th element of word.

Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 15 
Output : 1
Explanation : 15th index occurs in “best” and point to “e” which is 1st element of word.

Method #1 : Using enumerate() + list comprehension

In this, we use nested enumerate() to check indices for words, and strings in the list, list comprehension is used to encapsulate logic in 1 liner.

Python3




# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 20
 
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
 
# getting index of word
res = res[K]
 
# printing result
print("Index of character at Kth position word : " + str(res))


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #2 : Using next() + zip() + count()

In this, we pair up the number of words with their counts using zip(), and accumulate till we don’t reach Kth Index.

Python3




# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
 
from itertools import count
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 20
 
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(
    range(len(sub)), cnt) if idx == K)
 
# printing result
print("Index of character at Kth position word : " + str(res))


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method 3:  Using nested loop

Python3




# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using nested loop
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 20
 
# initializing index counter
idx = 0
 
# iterating over each word in the list
for word in test_list:
   
    # if the kth position is in the current word
    if idx + len(word) > K:
         
        # printing result
        print("Index of character at Kth position word : " + str(K - idx))
        break
     
    # if the kth position is not in the current word
    else:
        idx += len(word)
 
# if the kth position is beyond the end of the list
else:
    print("K is beyond the end of the list")


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2


Similar Reads

Python | Remove Kth character from strings list
Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + list sl
7 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Python Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
4 min read
Python | Kth index character similar Strings
Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Let’s discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension + lower() This problem can be solved using the co
3 min read
Python - Groups Strings on Kth character
Sometimes, while working with Python Strings, we can have a problem in which we need to perform Grouping of Python Strings on the basis of its Kth character. This kind of problem can come in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is one way in which this task can be performed.
4 min read
Python | Find frequency of given character at every position in list of lists
Given a list of lists, the task is to find the frequency of a character at every position of sub-list in list of lists. Input : lst = [['X', 'Y', 'X'], ['Z', 'Y', 'X'], ['Y', 'Y', 'Y'], ['Z', 'Z', 'X'], ['Y', 'Z', 'X']], character = 'X' Output: [0.2, 0.0, 0.8] Explanation: We have 3 elements in each sublist, we have to find position of 'X' at posit
5 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Python program for most frequent word in Strings List
Given Strings List, write a Python program to get word with most number of occurrences. Example: Input : test_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] Output : gfg Explanation : gfg occurs 3 times, most in strings in total. Input : test_list = ["geeks love gfg", "geeks are best"] Output : geeks Explanation : geeks occurs 2
6 min read
Python - Kth word replace in String
Sometimes, while working with String list, we can have a problem in which we need to replace the most Kth word of string. This problem has many applications in the web development domain. Let’s discuss a way in which this problem can be solved. Method 1: Using split() + join() This is way in which we can perform this task. In this, we break element
6 min read
Python - Test for Word construction from character list
Given a List and a String, test if the string can be made from list characters. Examples: Input : test_list = ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k'], test_str = 'geeks4geeks' Output : True Explanation : String can be made according to character frequencies.Input : test_list = ['s', '4', 'g', 'g', 'e', 's', 'e', 'e',
6 min read
three90RightbarBannerImg