1 / 10

Dynamic Lists

Dynamic Lists. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Dynamic Lists. List sizes in Python can change dynamically Append new elements to end Insert new elements into list Remove elements from list Implemented as methods on list variables

arva
Download Presentation

Dynamic Lists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dynamic Lists CSIS 1595: Fundamentals of Programming and Problem Solving 1

  2. Dynamic Lists • List sizes in Python can change dynamically • Append new elements to end • Insert new elements into list • Remove elements from list • Implemented as methods on list variables • Not true of all data types (arrays in C, etc.) • Common data structure in programming

  3. Dynamic List Methods • list.append(element) • Adds elementto end of list • Increases size of list by 1

  4. Dynamic List Methods • list.insert(i, element) • Inserts elementbefore the element at index iof list • Increases size of listby 1 • Inserting at 0 puts new element at beginning of list • Can’t insert at end – must use append instead

  5. Dynamic List Methods • list.remove(element) • Removes the first instance of element fromlist • Decreases size of listby 1 • Error if no such element in list

  6. Creating New Lists • Use [] to create new empty list • Can then append elements as needed • Shortcut: list = [value for index in range(0, size)]

  7. Other Useful Methods • len(list) number of elements in list • Useful for iteratingthrough dynamic list • May not know how many elements are currently in list!

  8. Other Useful Methods • list.count(element) • Returns number of timeselement found in list • 0 if elementnotin list • Useful for avoiding errors when removing elements • Check whether count > 0 first

  9. Example: Sorted Lists • Goal: • User repeatedly enters numbers to store in list • Keep list sorted from lowest to highest • Idea: • Find where new number should be placed and insertthere • Algorithm: • If list empty (length == 0) then append to end • If new number greater than any so far, append to end • New number > number at index length – 1 • Else loop from start of list until find element > new number • Insert new number at that point

  10. Example: Sorted Lists

More Related