Question

Deletion of List Elements The del statement removes an element or slice from a list by position....

Deletion of List Elements

  • The del statement removes an element or slice from a list by position.
  • The list method list.remove(item) removes an element from a list by it value (deletes the first occurance of item)
  • For example:
        
    a = ['one', 'two', 'three']
    del a[1]
    for s in a:
        print(s)
    
    b = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b']
    del b[1:5]
    print(b)
    
    b.remove('a')
    print(b)
        
    # Output:
    '''
    one
    three
    ['a', 'f', 'a', 'b']
    ['f', 'a', 'b']
    '''
    
  • Your textbook documents other List Methods in section 10.14. You can also find the more complete documentation of List methods here in the Python documenation.

Reference Variables

  • A reference variable stores the memory address of an object. It's similar to the C++ concept of a pointer. So when we access a reference variable, it indicates where to find the actual data we want, and we get it from there automatically. This allows two different reference variables to refer to the same actual object (the same memory address).
  • In Python, all variables are objects, so they all use reference variables. But in many other languages, such as C++ and Java, simple data (such as ints and floats) are stored directly, without reference variables.
  • To avoid confusion and mistakes, the common data types are all immutable in Python, so that we don't have to worry about modifying shared data. This includes strings, ints, floats, and bools.
  • Since lists are mutable, we have to be more careful about references to shared data, and knowing whether or not we are changing it.
  • None - keyword indicating an empty reference. This is similar to null in Java. A variable whose value is None is one that doesn't refer to an object.
  • For example, if you assign a variable to store the return value of a function that doesn't have a return statement, the variable will store None.
  • The is operator returns True if two reference variables refer to the same object (the same memory location). Otherwise it returns False.
  • The == operator compares the contents of its arguments (list elements), to see if they have the same value.
  • To copy a list, so that you have two separate objects storing the same data as each other, you can use a slice like this:
    list1 = [1, 2, 3, 4]
    list2 = list1[:]
    print(list1 is list2)  # False
    print(list1 == list2)  # True
       
  • The CodeLens example on this page from the book demonstrates "is" and "==" with reference variables well.

Lists and Functions

  • An entire list can be passed as an argument to a function.
  • The variable you use to refer to the list is really just a reference to the array's contents. Since a list is mutable, its contents may be changed by the function.
  • Example: ArrayParam.py.txt - Demonstrates how array parameters work
  • In-class exercise: write the method inputList to make this program work as shown.
# CS 110A - Starting poing for in-class exercise on List References and Functions


def main():
    a = []
    inputList(a)
    print("Here are the names you entered (excluding Craig):")
    for item in a:
        print(item)


# Insert your code here 
# Write the inputList function so that the program produces the output below.


main()

# Sample output:
'''
Please input one name on each line, hitting Enter on a blank line when finished:
 Craig
 Indika
 Deepa
 Man
 
Here are the names you entered (excluding Craig):
Indika
Deepa
Man
'''
'''
Please input one name on each line, hitting Enter on a blank line when finished:
 Erez
 Dan
 Craig
 Anita
 Henry
 
Here are the names you entered (excluding Craig):
Erez
Dan
Anita
Henry
'''
0 0
Add a comment Improve this question Transcribed image text
Answer #1

def main():
a = [] # creating empty list
inputList(a) # calling method below
print("Here are the names you entered (excluding Craig):")   
for item in a:
print(item) # printing elements of modified list a
# Insert your code here
# inputlist function that takes empty list, asks user to enter names, store them in list and removes Craig from it
def inputList(a):
print('Please input one name on each line, hitting Enter on a blank line when finished:') # printing instruction
name = raw_input(); # taking input name
while ( name !=''): # looping until user presses Enter (name = '' )
a.append(name) # this functions adds new element (name) to list a
name = raw_input(); # taking input again
a.remove('Craig') # removing first occurance of name 'Craig'
main()

1 def main(): 2 3 inputlist (a) 4 print( Here are the names you entered (excluding Craig):) 5 for item in a: creating empty

Sample outputs:

Please input one name on each line, hitting Enter on a blank line when finished: Craig Indika Deepa Man Here are the names yo

Please input one name on each 1line, hitting Enter on a blank line when finished: Erez Dan Cra1g Anita Henry Here are the nam

Add a comment
Know the answer?
Add Answer to:
Deletion of List Elements The del statement removes an element or slice from a list by position....
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
  • Write a Python program (remove_first_char.py) that removes the first character from each item in a list...

    Write a Python program (remove_first_char.py) that removes the first character from each item in a list of words. Sometimes, we come across an issue in which we require to delete the first character from each string, that we might have added by mistake and we need to extend this to the whole list. Having shorthands (like this program) to perform this particular job is always a plus. Your program should contain two functions: (1) remove_first(list): This function takes in a...

  • Something is preventing this python code from running properly. Can you please go through it and...

    Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...

  • C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a...

    C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a structure called MyToDo to hold information about each todo item. The members of the MyToDo struct are description, due date, and priority. Each of these items will be stored in an array called ToDoList. The definition for the MyToDo struct should be placed in the header file called ToDo.h Visually think of the ToDoList like this: There are two ways to add items to...

  • Write three object-oriented classes to simulate your own kind of team in which a senior member...

    Write three object-oriented classes to simulate your own kind of team in which a senior member type can give orders to a junior member type object, but both senior and junior members are team members. So, there is a general team member type, but also two specific types that inherit from that general type: one senior and one junior. Write a Python object-oriented class definition that is a generic member of your team. For this writeup we call it X....

  • D Question 12 1.5 pts Check the true statements about NumPy arrays: O A single instantiated NumPy array can store multi...

    D Question 12 1.5 pts Check the true statements about NumPy arrays: O A single instantiated NumPy array can store multiple types (e.g., ints and strings) in its individual element positions. A NumPy array object can be instantiated using multiple types (e.g., ints and strings) in the list passed to its constructor O Memory freeing will require a double-nested loop. The number of bits used to store a particular NumPy array object is fixed. O The numpy.append(my.array, new_list) operation mutates...

  • QUESTION 21 while True: , in Python, can be used to create an infinite loop. True...

    QUESTION 21 while True: , in Python, can be used to create an infinite loop. True False 2 points    QUESTION 22 The Python Framework does inform you where an error occurred True False 2 points    QUESTION 23 ____ is a critical component to being able to store data and information long term. File Access Memory Print function with 2 points    QUESTION 24 Error handling is also known as ___ handling Result Recursion Exception Crash 2 points   ...

  • Solve the code below: CODE: """ Code for handling sessions in our web application """ from bottle import request, response import uuid import json import model import dbsche...

    Solve the code below: CODE: """ Code for handling sessions in our web application """ from bottle import request, response import uuid import json import model import dbschema COOKIE_NAME = 'session' def get_or_create_session(db): """Get the current sessionid either from a cookie in the current request or by creating a new session if none are present. If a new session is created, a cookie is set in the response. Returns the session key (string) """ def add_to_cart(db, itemid, quantity): """Add an...

  • SHORT ANSWER QUESTIONS Part 1 Classes Abstraction: What is Abstraction in terms of representation? Specifically what...

    SHORT ANSWER QUESTIONS Part 1 Classes Abstraction: What is Abstraction in terms of representation? Specifically what choices does one make when creating a class that is an example of Abstraction? Encapsulation: What is encapsulation? What is information hiding? What does a public interface to a class consist of (not in the sense of actual java interfaces but what the client uses to manipulate objects of the class) What is an object of a class? What is the constructor? How do...

  • I need this in C++. This is all one question Program 2: Linked List Class For...

    I need this in C++. This is all one question Program 2: Linked List Class For this problem, let us take the linked list we wrote in a functional manner in a previous assignment and convert it into a Linked List class. For extra practice with pointers we'll expand its functionality and make it a doubly linked list with the ability to traverse in both directions. Since the list is doubly linked, each node will have the following structure: struct...

  • 8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code...

    8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code Your answers to this homework must be your own work.You are not allowed to share your solutions.You may not engage in any other activities that will dishonestly improve your results or dishonestly improve or damage the results of others. Plagiarism Plagiarism is when you copy words, ideas, or any other materials from another source without giving credit. Plagiarism is unacceptable in any academic environment....

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