Three ways to delete a Python list

Source: Internet
Author: User
Tags python list

1. Delete elements using the DEL statement

Del statement after the value is removed from the list, it can no longer be accessed.

2. Delete elements using pop ()

Pop () removes the element at the end of the list and allows you to continue to use it. Appetite popping (pop) comes from the analogy that the list is a stack, and the element at the end of the delete list is the top element of the pop-up stack.

Action: If the motorcycle in the list is stored according to the purchase time, you can use the method pop () to print a message stating which motorcycle was last purchased:

#!/usr/bin/env pythonmotorcycles = [' Honda ', ' Yamaha ', ' Suzuki ']last_owned = Motorcycles.pop () print ("The Last Motorcycle I owned was a "+ last_owned.title () + '. ') ================================the Last motorcycle I owned is a Suzuki.

The element at any point in the pop-up list:

#!/usr/bin/env pythonmotorcycles = [' Honda ', ' Yamaha ', ' Suzuki ']last_owned = Motorcycles.pop (0) print ("The Last Motorcycle I owned was a "+ last_owned.title () + '. ') ========================================the Last motorcycle I owned is a Honda.

3. remove element by value
Motorcycles = [' Honda ', ' Yamaha ', ' Suzuki ']motorcycles.remove (' Yamaha ') print (motorcycles) ========================= ===========[' Honda ', ' Suzuki ']

Note: Remove () deletes only one of the specified values. If the value you want to delete may appear more than once in the list, you need to use a loop to determine whether all the values have been deleted.

Three ways to delete a Python list

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.