Python – Incremental Slice concatenation in String list


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.

Updated on: 06-Sep-2021

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements