Python program to extract characters in given range from a string list


When it is required to extract characters in given range from a string list, a list comprehension and list slicing is used.

Example

Below is a demonstration of the same −

my_list = ["python", "is", "fun", "to", "learn"]

print("The list is :")
print(my_list)

start, end = 11, 25

my_result = ''.join([element for element in my_list])[start : end]

print("The result is :")
print(my_result)

Output

The list is :
['python', 'is', 'fun', 'to', 'learn']
The result is :
tolearn

Explanation

  • A list is defined and displayed on the console.

  • The value for ‘start’ and ‘end’ are defined.

  • A list comprehension is used to iterate over the list, and every element between the ‘start’ and ‘end’ value is extracted, and then the 'join' method is used to remove the spaces.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements