Question

Python homework Write a function called insert_value(my_list, value, insert_position) that takes a list, a value and...

Python homework

Write a function called insert_value(my_list, value, insert_position) that takes a list, a value and an insert_position as parameters. The function returns a copy of the list with the value inserted into the list (my_list) at the index specified by insert_position.

Check for the insert_position value exceeding the list (my_list) bounds.

if the insert_position is greater than the length of the list, insert the value at the end of the list.

if the insert_position is less than or equal to zero, insert the value at the start of the list.

You must use a loop(s) in your solution. You may make use of the list_name.append(item) method in order to build the new list. You must not use built-in functions (other than the range() function), slice expressions, list methods (other than the append() method) or string methods in your solution.

This what I come up with the above. But I am not getting the answer correct.

def insert_value(my_list, value, insert_position):

    # get the length of the list    

    count = 0

    for item in my_list:

        count += 1

    new_list = []

    for i in range(0,  count + 1):        

        if insert_position > i:

            new_list.append(my_list[i])    

        elif insert_position == i:

            new_list.append(value)

        else:

            new_list.append(my_list[i-1])

    return new_list

str_list3 = ['one','three','four', 'five', 'six']

new_list = insert_value(str_list3, 'two', 1)

print(new_list)

str_list4 = ['i', 't']

str_list4 = insert_value(str_list4, 'p', 0)

print(str_list4)

str_list4 = insert_value(str_list4, 's', -1)

print(str_list4)

str_list4 = insert_value(str_list4, 's', 7)

print(str_list4)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

def insert_value(my_list,value,insert_position):
#Initializing a new list for the copy of my_list
    new_list = []
#Finding the length of my_list
    count = 0
    for i in my_list:
        count += 1
#Check if the insert_position is greater than or equal length
#return the new list by copying my_list into new_list append
#appending value to the list end
    if insert_position >= count:
        new_list = my_list
        new_list.append(value)
        return new_list
#Check if the insert_position is less than or equal to 0
#return the new list by first appending value into new_list and
#appending my_list to the list end
    if insert_position <= 0       :
        new_list.append(value)
        for i in range(count):
            new_list.append(my_list[i])
        return new_list
#Iterate through each index of the list and check index = insert_position
#append new_list with my_list until index = insert_position
#if index equals insert_position append the value and append remaining
#my_list to new_list
    else:
        for i in range(count):
            if (i == insert_position):
                new_list.append(value)
            new_list.append(my_list[i])
        return new_list

#Test run of the function
print insert_value(['a','b','c'],'test',2)
print insert_value(['a','b','c'],'test',6)
print insert_value(['a','b','c'],'test',0)
print insert_value(['a','b','c'],'test',-1)



SAMPLE OUTPUT:

Add a comment
Know the answer?
Add Answer to:
Python homework Write a function called insert_value(my_list, value, insert_position) that takes a list, a value and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python Question? Write a function called reverse(user_list, num = -1) that takes a list and a...

    Python Question? Write a function called reverse(user_list, num = -1) that takes a list and a number as parameters. The function returns a copy of the list with the first number of items reversed. Conditions: The number parameter must be a default argument. -      If the default argument for number is given in the function call, only the first number of items are reversed. -      If the default argument for number is not provided in the function call, then the...

  • write a Python function that takes in a list of integers and returns maximum and minimum values in the list as a tuple

    1 write a Python function that takes in a list of integers and returns maximum and minimum values in the list as a tuple. Hint (can be done in one pass, you are not allowed to use built-on min and max functions.)max, min = find_max_min(my_list):2 write a Python function that takes in a list of integers (elements), and an integer number (num). The functions should count and return number of integers in elements greater than, less than, and equal to...

  • 1.Write a function called high_point that takes a list of integers and returns True if there...

    1.Write a function called high_point that takes a list of integers and returns True if there exists a value in the list that is bigger than the values immediately before and after it in the list. Your function must return False if no such value exists. The values in the beginning and the end of the list cannot be high points. (20 points) Test Cases: print(high_point([2,5,8,9,7,9])) True print(high_point([2,5,6,6,3])) False print(high_point([2,5,8,21,22])) False 2. Write a while loop to repeatedly ask for...

  • solve with python Write a recursive function recStringWithLenCount() that takes a one-dimensional list of strings as...

    solve with python Write a recursive function recStringWithLenCount() that takes a one-dimensional list of strings as a parameter and returns the count of strings that have at least the length of second parameter passed into the function that are found in the list. Recall that you can determine whether an item is a string by writing type(item) == str. The only list functions you are allowed to use are len(), indexing (lst[i] for an integer i), or slicing (lst[i:j] for...

  • Write in C++: Please create a shopping list using the STL list container, then follow the...

    Write in C++: Please create a shopping list using the STL list container, then follow the following instructions. Create an empty list. Append the items, "eggs," "milk," "sugar," "chocolate," and "flour" to the list. Print the list. Remove the first element from the list. Print the list. Insert the item, "coffee" at the beginning of the list. Print the list. Find the item, "sugar" and replace it with "honey." Print the list. Insert the item, "baking powder" before "milk" in...

  • Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface:...

    Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface: /** * An ordered list of items. */ public interface ItemList<E> {      /**       * Append an item to the end of the list       *       * @param item – item to be appended       */ public void append(E item);      /**       * Insert an item at a specified index position       *       * @param item – item to be...

  • Python: Create a function count_target_in_list that takes a list of integers and the target value then...

    Python: Create a function count_target_in_list that takes a list of integers and the target value then counts and returns the number of times the target value appears in the list. Write program in that uses get_int_list_from_user method to get a list of 10 numbers, then calls the count_target_list method to get the count then prints the number of times the target was found in the list. def get_int_list_from_user(): lst=[] y = int(input("Enter number of numbers")) for x in range(y): lst.append(int(input("Enter...

  • Write a function decompressed(count_tuples) that takes a list of counts of '0's and '1's as defined...

    Write a function decompressed(count_tuples) that takes a list of counts of '0's and '1's as defined above and returns the expanded (un-compressed) string. You may assume that the first value of count_tuples has a count that is greater than or equal to zero and all other counts are greater than zero. Comments to show how to figure this out would be greatly appreciated A data file in which particular characters often occur multiple times in a row can be compressed...

  • Python 2.7 Write a function cumsum() that takes a list l as argument and returns the...

    Python 2.7 Write a function cumsum() that takes a list l as argument and returns the cumulative sum (also known as the prefix sum) of l, which is a list, say cs of the same length as l such that each element cs[i] is equal to the sum of the first i + 1 elements of l, i.e., cs[i] == l[0] + l[1] + l[2] + ... + l[i] You should not modify the argument list l in any way....

  • Questin 1 (CO 2) Which of the following is not a valid name in python? last_name...

    Questin 1 (CO 2) Which of the following is not a valid name in python? last_name lastName last name lname Question 2 (CO 3) How many times will “Hello World” be displayed after the following code executes? num=2 while num<12:     print("Hello world")     num+=2 2 12 5 4 Question 3 (CO 1) The following code contains an error, what type of error is it and what line number is it? 1 count=1 2 while count<4 3    print("count = ",...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT