Python: Lists: Take a Slice, Delete Elements, Popping Elements

Go to Chapter 17 of A Smarter Way.

Return to our lists page:
http://introtopython.org/lists_tuples.html#Want-to-see-what-functions-are?
…and scroll down slightly because the page TOC is (again) broken.

Taking a slice from a list:

friends = ['bill', 'jeff', 'jim', 'scott', 'joel']

# Grab the first three users in the list.
first_three = friends[0:3]

for friend in first_three:
    print(friend.title())

Now go to Chapter 18 of A Smarter Way.

Remove an item by position:

del friends[0]

Remove an item by value:

friends.remove('jeff')

Now go to Chapter 19 of A Smarter Way.

Popping an element:

This is a unique operation. Popping an item removes the top item from a list, and passes it to a variable or other operation:

first_friend = friends.pop(0)

Exercises

See http://www.asmarterwaytolearn.com/python/17.html,
http://www.asmarterwaytolearn.com/python/18.html and
http://www.asmarterwaytolearn.com/python/19.html

See http://introtopython.org/lists_tuples.html#Want-to-see-what-functions-are? … and scroll down slightly.

  1. Continue editing examples.py.
  2. Slice a range of items from your list.
  3. Delete one item by index.
  4. Delete one item by value.
  5. Pop a value from the list, put it into a
  6. Perform a test to see if an item is in your list.