New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming Python Strings and Lists

Strings and Lists

🐍 Python

Index, slice and modify strings and lists.

Lesson 4 of 7 Tutorial
0/7 completed

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 items
  • list.append(x) — add x to the end
  • list.insert(i, x) — add x at index i
  • list.remove(x) — remove first occurrence of x
  • list.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

Lesson sections