Whats the best way to remove print brackets from a python list? -


the function below inserts list list @ specified location.

what's best way remove middle brackets output while leaving outer brackets on?

def insert(list1, list2, index):      pos = 0     new_list = []      if index > len(list1):         index = len(list1)     elif index < 0:         index = 0      pos in range(0, index):         new_list.append(list1[pos])      #for pos in range(1):     new_list.append(list2)      while index != len(list1):         new_list.append(list1[index])         index += 1      return new_list   list1 = ["b", "o", "o", "m"] list2 = ["r", "e", "d"] index = 2  new_list = insert(list1, list2, index) print(new_list) 

output:

['b', 'o', ['r', 'e', 'd'], 'o', 'm'] 

you can use list slicing desired results:

list1 = ["b", "o", "o", "m"] list2 = ["r", "e", "d"] index = 2  print list1[:index]+list2+list1[index:] >>> ['b', 'o', 'r', 'e', 'd', 'o', 'm'] 

to break down, list slicing works lst[start:end] so,

list1 = ["b", "o", "o", "m"] index = 2 print list1[:index] >>> ['b', 'o']  print list1[index:] >>> ['o', 'm'] 

so divided list 2 parts , use + operator concatenates lists join first part, list2 , second part , in result final list.

if want encapsulate things inside function then:

def insert(list1, list2, index):     return  list1[:index]+list2+list1[index:] 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -