1/32
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
Lists
Ordered, mutable (changeable) collections of items
Tuples
Ordered, immutable (unchangeable) collections of items
Why Use Lists?
Versatile for storing and manipulating data that might change, like user inpts, evolving datasets, or temporary storage
Why Use Tuples?
Useful for representing fixed collections of data (like coordinates), returning multiple values from functions, or ensuring data integrity where changes are not desired
Differences In Mutability (Lists & Tuples)
Lists can be modified after creation; tuples cannot
Syntax Difference (Lists & Tuples)
Lists use square brackets
Creating Lists
Empty list: my_list = []
With elements: my_list = [1, “hell0”, 3.14]
Creating Tuples
Empty tuple: my_tuple = ()
With elements: my_tuple = (1, “hello”, 3.14)
Accessing Elements (Indexing)
Uses square brackets [] with an index
0-based Indexing
The first element is at index 0
Slicing (Extracting Sub-sequence) Syntax
sequence[start:end:step]
Slicing Start
Inclusive index (defaults to 0)
Slicing End
Exclusive index (defaults to the end of the sequence)
Slicing Step
The increment (defaults to 1)
len(my_list) or len(my_tuple)
Returns the number of elements
Concatenation (Joining)
Uses the + operator
Important About Concatenation
Creates a new list/tuple - does not modify the originals
Repetition
Uses the * operator (with an integer)
Important About Repetition
Creates a new list/tuple
Repetition Code
repeated_list = my_list * 3
my_list.append(item)
Adds item to the end of the list - modifies the list in-place
my_list.extend(another_list)
Appends all elements from another_list to the end of my_list - modifies my_list in-place
Constrast Between Extending And “+”
+ creates a new list; extend modifies the existing one
my_list.insert(index, item)
Inserts item at the specified index - modifies the list in_place
my_list.pop()
Removes and returns the last element - modifies the list in-place
my_list.pop(index)
Removes and returns the element at the specified index - modifies the list in-place
my_list.remove(value)
Removes the first occurrence of value - modifies the list in-place
Caution Of Removing By Value
Raises a ValueError if the value is not found
del my_list[index]
Removes the element at index - modifies the list in-place
del my_list[start:end]
Removes a slice
my_list[index] = new_value
Changes the element at index
my_list[start:end] = another_list
Replaces a slice with elements from another list (sizes don’t have to match)
for item in sequence: Loop
Iterates directly over elements - simple and readable