Lists Flashcards
Lists are a fundamental data structure in Python that allow you to “_____” & “________” collections of items
Store & manipulate
They are “_______” and “____” hold items of different data types, such as numbers, strings, or even other lists
Versatile; and
COMPARED to strings = which are limited
Lists are “_______”, meaning you can modify their elements by adding, removing, or changing values
Mutable
COMPARED to strings which are not mutable
How do you create a list?
Are created by enclosing items in square brackets [ ] and separating them with commas
Can make “mixed” lists
Ex.
List of 5 integers:
numbers = [10, 20, 30, 40, 50]
How can list elements be accessed?
Indexing starts at “__”
Can be accessed using index values
Similar to characters in a string
Indexing starts at 0
How do you access multiple elements in a list?
Give an example
You can use list slicing which allows you to extract a portion of a list
Syntax: my_list[start:end:step]
- start is the starting index
- end is the ending index (exclusive)
- step is the step size
How do you modify list elements after they were initialized?
Give an example
Elements can be modified by assigning a new value to a specific index
Ex.
my_list = [10, 20, 30, 40, 50]
Modifying the second element: my_list[1] = 25
Resulting list: [10, 25, 30, 40, 50]
True or false. Lists support various operations, such as concatenation, repetition, and membership testing (similar to string operations)
True
Concatenation: Combining two or more lists using the + operator.
Repetition: Repeating a list a certain number of times using the * operator.
Membership testing: Checking if an item is present in a list using the in and not in operators.
What are 3 different ways to traverse a list with loops?
- With for loop iterating over list items:
for i in list:
print(i) - With for loop using range and indexing:
for i in range(len(list)):
print( list[i] ) - With while loop using indexing:
length = len(list)
i = 0
while i < length:
print(list[i])
i += 1
How is the append() method used for lists?
Give an example
Used to add an element to the end of a list
This method modifies the list in-place, meaning it alters the original list rather than creating a new one
list_name.append(element)
SIMILAR to the use of the += operator
Ex.
numbers = [1, 2, 3, 4]
numbers.append(5)
Result [1, 2, 3, 4, 5].
If you want to combine MULTIPLE lists the “____” operator is more efficient
+=
list = [1,2,3,4]
toadd = [5,6]
list += toadd
[1, 2, 3, 4, 5, 6]
If you want to combine a SINGLE element to a list the “______” method is a better choice
.append()
list = [1,2,3,4]
toadd = [5,6]
list.append(toadd)
[1, 2, 3, 4, [5, 6]]