Lists And 2D Lists Flashcards
What is a list in Python?
A list is a data structure that can store multiple items in one variable.
Example: my_list = [1, 2, 3].
How do you access an item in a list?
Use the index, starting from 0.
Example: my_list[1] returns 2.
How do you change an item in a list?
Assign a new value to an index.
Example: my_list[0] = 10 changes the first item to 10.
How do you add an item to the end of a list?
Use append().
Example: my_list.append(4) adds 4 to the end.
How do you insert an item at a specific position in a list?
Use insert(index, value).
Example: my_list.insert(1, 99) adds 99 at index 1.
How do you remove an item from a list by value?
Use remove(value).
Example: my_list.remove(3) removes the first 3.
How do you remove an item from a list by index?
Use pop(index) or del my_list[index].
Example: my_list.pop(2) removes the item at index 2.
How do you loop through a list in Python?
Use a for loop like for item in my_list: to access each item one at a time.
What is a 2D list in Python?
A list of lists.
Example: matrix = [[1, 2], [3, 4], [5, 6]].
How do you access an item in a 2D list?
Use two indexes.
Example: matrix[1][0] returns 3.
How do you change an item in a 2D list?
Use two indexes to assign a value.
Example: matrix[2][1] = 9.
How do you loop through a 2D list in Python?
Use nested loops: for row in matrix: and then for item in row:.
What are common uses of 2D lists?
Representing data tables, grids, spreadsheets, or game boards like tic-tac-toe.
What is the difference between a list and a 2D list?
A list stores a single sequence of items. A 2D list stores lists within a list, forming rows and columns.