A Python list is a mutable, ordered sequence that stores references to elements. It can hold strings, numbers, or other Python data types, preserving insertion order and supporting zero-based indexing. section 3.3 section 3.8
Create and inspect lists incrementally:
- Create an empty list with list() or [], then use len(items) to count elements. section 3.3
- Add one element with append(); add the elements of another list with extend(). section 3.3.1 section 13.3.1
- Check membership with x in items before using index() or remove(), because absent values raise exceptions. section 3.3.5 section 3.3.6
- Mutate elements by index, remove values with remove(), or remove and return an element with pop(); sort() and reverse() change the list. section 3.3.6 section 3.3.8
- Use slices to extract smaller lists, join() to create a string, and list comprehensions or map() to build new lists. section 3.8 section 13.3.2
Formatting picnic items
items = ['salad', 'chips', 'cupcakes'] if len(items) == 1: message = items[0] elif len(items) == 2: message = ' and '.join(items) else: message = ', '.join(items[:-1]) + ', and ' + items[-1] print(f'You are bringing {message}.') # You are bringing salad, chips, and cupcakes. section 3.2
Building a verse from mutable lines
gifts = ['A partridge in a pear tree.', 'Two turtle doves,', 'Three French hens,'] lines = ['On the third day of Christmas,', 'My true love gave to me,'] lines.extend(reversed(gifts[:3])) lines[-1] = 'And ' + lines[-1].lower() print('\n'.join(lines)) section 13.3.1
| The items for the list will be passed as positional arguments. When there is only one item, you’ll print that: $ ./picnic.py salad You are bringing salad. |
|
Shows the smallest list-formatting case: one positional item becomes a complete sentence. section 3.0





















