Inserting a list into another list using only loops:
I am using the current version of python. I need to return a copy of list1 with list2 inserted at the position indicated by the index, i.e. If the index value is 2, list2 is inserted into list 1 at position 2. I can only use for loops / while, the range and name function list_name.append (value), and lists cannot be sliced. So if list1 list1 = list of arrows2 = red and index value = 2, how do I return the new list = boredom? I have this so far:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
index = 2
new_list = []
if index > len(list1):
new_list = list1 + list2
print (new_list)
if index <= 0:
new_list = list2 + list1
print (new_list)
source to share
An alternative approach to Padriac is using three loops for
:
list1 = ['b','o','o','m']
list2 = ['r','e','d']
n = 2
new_list = []
for i in range(n): # append list1 until insert point
new_list.append(list1[i])
for i in list2: # append all of list2
new_list.append(i)
for i in range(n, len(list1)): # append the remainder of list1
new_list.append(list1[i])
source to share
Once you hit the index, use the inner loop to add each item from list2:
for ind, ele in enumerate(list1):
# we are at the index'th element in list1 so start adding all
# elements from list2
if ind == index:
for ele2 in list2:
new_list.append(ele2)
# make sure to always append list1 elements too
new_list.append(ele)
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
If you must use a range, just replace the enum with a range:
new_list = []
for ind in range(len(list1)):
if ind == index:
for ele2 in list2:
new_list.append(ele2)
new_list.append(list1[ind])
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']
Or without ifs using expansion and removal if allowed:
new_list = []
for i in range(index):
new_list.append(list1[i])
list1.remove(list1[i])
new_list.extend(list2)
new_list.extend(list1)
Adding as soon as we hit the index means the items will be inserted from the correct index, items from list1 should always be added after your check.
source to share
Check out this little piece of code I wrote. Check the condition while
that is being used. I hope he answers your question.
email = ("rishavmani.bhurtel@gmail.com")
email_split = list(email)
email_len = len(email)
email_uname_len = email_len - 10
email_uname = []
a = 0
while (a < email_uname_len):
email_uname[a:email_uname_len] = email_split[a:email_uname_len]
a = a + 1
uname = ''.join(email_uname)
uname = uname.replace(".", " ")
print("Possible User Name can be = %s " %(uname))
source to share