|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Declare a list with the items 1, 2 |
| 4 | +alist = [1, 2] |
| 5 | +print("Our list:", alist) |
| 6 | + |
| 7 | +# Appends an element to the end of the list |
| 8 | +alist.append(5) |
| 9 | +print("Our list:", alist) |
| 10 | + |
| 11 | +# Appends all the elements in an iterable to 'alist' |
| 12 | +anotherlist = [3, 4] |
| 13 | +alist.extend(anotherlist) |
| 14 | +print("Our list:", alist) |
| 15 | + |
| 16 | +# Inserts an item, x, at a given position, i, in a list (list.insert(i,x)) |
| 17 | +alist.insert(1, 9) |
| 18 | +print("Our List:", alist) |
| 19 | + |
| 20 | +# Removes the first item from the list with value x (list.remove(x)) |
| 21 | +alist.remove(9) |
| 22 | +print("Our List:", alist) |
| 23 | + |
| 24 | +# Remove and return an item from a list at a given position, i |
| 25 | +# If no argument is given, remove and return the last element from the list |
| 26 | +alist.pop(1) |
| 27 | +print("Our List:", alist) |
| 28 | + |
| 29 | +# Return the index of the first item with value x in the list |
| 30 | +# Can take an option start and/or end index (list.index(x[, start[, end]])) |
| 31 | +print("Index:", alist.index(1)) |
| 32 | + |
| 33 | +# Count the number of times an item, x, appears in the list |
| 34 | +print("Number of occurrences", alist.count(1)) |
| 35 | + |
| 36 | +# Reverses the items of the list, in place |
| 37 | +alist.reverse() |
| 38 | +print("Our list:", alist) |
| 39 | + |
| 40 | +# blist is a pointer to alist |
| 41 | +blist = alist |
| 42 | +# blist is a shallow copy of alist |
| 43 | +blist = alist.copy() |
| 44 | + |
| 45 | +# remove all items from a list (equivalent to del alist[:]) |
| 46 | +print("Our list:", blist) |
| 47 | +blist.clear() |
| 48 | +print("Our list:", blist) |
| 49 | + |
0 commit comments