Python – Incremental Slice concatenation in String list

PythonServer Side ProgrammingProgramming

When it is required to display incremental slice concatenation in string list, a simple iteration and list slicing is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = ['pyt', 'is', 'all', 'fun']

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

my_result = ''
for index in range(len(my_list)):

   my_result += my_list[index][:index + 1]

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

Output

The list is :
['pyt', 'is', 'all', 'fun']
The result is :
pisallfun

Explanation

  • A list is defined and displayed on the console.

  • An empty string is created.

  • The list is iterated over, and the element is concatenated with the consecutive element.

  • This result is assigned to a variable.

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

raja
Published on 06-Sep-2021 08:07:44
Advertisements