5 Week
5 Week
Lists are
essential for any programming language because they allow us to store, organize, and
manipulate data.
“First, we’re going to look at how to create and access lists. Lists can hold different types of
data, like strings, numbers, or even a mix of both. Let’s create a list of fruits: fruits =
["apple", "banana", "cherry"]. You can see that this list contains three items: 'apple',
'banana', and 'cherry'. To access any item, we use an index. In Python, lists are zero-indexed,
meaning the first item is at index 0. So if we want to access the first item, we’d write:
print(fruits[0]). This will output ‘apple.’”
“Next, let’s talk about modifying lists. Lists are mutable, which means you can change them after
they’re created. You can add an item to the end of the list using .append(). Let’s say we want
to add ‘orange’ to our fruits list: fruits.append("orange"). Now our list includes ‘apple,’
‘banana,’ ‘cherry,’ and ‘orange’.”
“We can also remove items from a list. To remove ‘banana,’ we could use the .remove()
method, like this: fruits.remove("banana"). Or, we could use the del keyword to delete
an item by its index. For example, del fruits[1] will remove the second item in our list.”
“Finally, here are some other basic list operations. If you want to know how many items are in a
list, you can use len(fruits). To find the index of a specific item, you can use .index(),
like fruits.index("cherry"). And if you want to combine lists, you can use the + operator
to concatenate two lists.”
“If you want to add multiple items at once, you can use .extend(). Suppose we want to add
‘mango’ and ‘grape’ to our fruits list. We’d write fruits.extend(["mango", "grape"]).
Now, the list has more items in it, and the final list is ['apple', 'kiwi', 'banana',
'cherry', 'orange', 'mango', 'grape'].”
Slices
s = 'abcdefg'
print(s[1:-1]) #This slice starts at index 1 and goes up to, but does not
include, the last character (-1)
print(s[:3]) #the slice starts at the beginning of the string and goes up
to, but does not include, index 3.
print(s[2:]) #This slice starts at index 2 and goes to the end of the
string
print(s[:-1]) #this slice goes from the beginning of the string up to, but
does not include, the last character.
https://quizizz.com/admin/quiz/6704c23d2b8f5123c26133f6?at=6704c73999be8d4d15b5bb26&
MCQ_saved=true