Strings Are Like Lists of Characters
In Python a string behaves like a list of characters. You can grab a single character with an index and a slice of a string with brackets.
name = "Python"
print(name[0]) # P (index starts at 0)
print(name[0:3]) # Pyt (slicing position 0 up to 3)
print(name.upper()) # PYTHON
print(len(name)) # 6
Remember: indexes start at 0, and a slice [start:end] stops BEFORE the end position.
Lists Hold Many Values
fruits = ["mango", "orange", "pawpaw"]
fruits.append("banana") # add to the end
fruits[1] = "apple" # change an item
print(fruits) # ['mango', 'apple', 'pawpaw', 'banana']
for f in fruits:
print(f)
Useful Methods
len(list)— number of itemslist.append(x)— add x to the endlist.insert(i, x)— add x at index ilist.remove(x)— remove first occurrence of xlist.sort()— sort in place
Challenge
Make a list of your top five movies. Print the first movie, the second-to-last movie, and then the whole list sorted.
Example
fruits = ["mango", "orange"]
fruits.append("pawpaw")
print(fruits[0])
print(fruits)
Lesson Nav
Course contents
Python Course
0/7 lessons completed