Python Lists Summary
Overview of Lists in Python
Definition: A list is an ordered collection of items.
Syntax: Indicated by square brackets
[], separated by commas. Example:cars = ['Suzuki', 'Toyota', 'Honda', 'Changan']
Accessing Elements
Indexing: Elements accessed via their index position, starting from 0.
Negative Indexing:
-1indicates the last item.Example:
bicycles[-1]returns the last bicycle.
Modifying Lists
Changing Elements: Modify using the index. Example:
motorcycles[0] = 'ducati'.Appending: Use
append()to add items. Example:motorcycles.append('ducati').Inserting: Use
insert(index, item)to add at a specific index. Example:motorcycles.insert(0, 'ducati').Removing: Use
del,pop(), orremove()to delete items from a list.del motorcycles[0]removes by index.popped_motorcycle = motorcycles.pop()removes and stores the last item.motorcycles.remove('ducati')removes by value.
Organizing a List
Sorting: Use
sort()for permanent sorting,sorted()for temporary sorting.Reversing: Use
reverse()to reverse the order of the list.
List Length and Errors
Length: Use
len(list). Example:len(cars)returns the number of items.Index Errors: Occur when accessing an index out of range. Use negative indexing to access from the end, but remember it can also produce errors with empty lists.