Lists Basics

Creating Lists

  1. # create list
  2. fruits = ["apple", "banana", "cherry"]
  3. numbers = [1, 2, 3, 4, 5]
  4. mixed = [1, "two", 3.0, True]
  5. empty = []

Accessing Elements

  1. # indexing
  2. fruits = ["apple", "banana", "cherry"]
  3. fruits[0]
  4. #ans: "apple"
  5. fruits[-1]
  6. #ans: "cherry"
  7. fruits[1]
  8. #ans: "banana"

Slicing

  1. # slice lists
  2. numbers = [0, 1, 2, 3, 4, 5]
  3. numbers[1:4]
  4. #ans: [1, 2, 3]
  5. numbers[:3]
  6. #ans: [0, 1, 2]
  7. numbers[3:]
  8. #ans: [3, 4, 5]

List Length

  1. # len() function
  2. fruits = ["apple", "banana", "cherry"]
  3. len(fruits)
  4. #ans: 3
  5. len([])
  6. #ans: 0

Modifying Elements

  1. # change element
  2. fruits = ["apple", "banana", "cherry"]
  3. fruits[1] = "blueberry"
  4. #ans: fruits is ["apple", "blueberry", "cherry"]

Exercises - Part 1

  1. # what is the first element?
  2. lst = [10, 20, 30]
  3. lst[0]
  4. #ans: 10

Exercises - Part 2

  1. # negative index?
  2. lst = [10, 20, 30]
  3. lst[-1]
  4. #ans: 30
  5. lst[-2]
  6. #ans: 20

Exercises - Part 3

  1. # slicing result?
  2. lst = [1, 2, 3, 4, 5]
  3. lst[1:4]
  4. #ans: [2, 3, 4]

Exercises - Part 4

  1. # what happens?
  2. lst = [1, 2, 3]
  3. lst[5]
  4. #ans: IndexError

Exercises - Part 5

  1. # empty slice?
  2. lst = [1, 2, 3]
  3. lst[5:10]
  4. #ans: []

Exercises - Part 6

  1. # step in slice?
  2. lst = [0, 1, 2, 3, 4, 5]
  3. lst[::2]
  4. #ans: [0, 2, 4]

Exercises - Part 7

  1. # reverse list?
  2. lst = [1, 2, 3]
  3. lst[::-1]
  4. #ans: [3, 2, 1]

Exercises - Part 8

  1. # modify with slice?
  2. lst = [1, 2, 3, 4, 5]
  3. lst[1:3] = [20, 30]
  4. #ans: [1, 20, 30, 4, 5]

Exercises - Part 9

  1. # nested list access?
  2. matrix = [[1, 2], [3, 4]]
  3. matrix[0][1]
  4. #ans: 2

Exercises - Part 10

  1. # list concatenation?
  2. lst1 = [1, 2]
  3. lst2 = [3, 4]
  4. lst1 + lst2
  5. #ans: [1, 2, 3, 4]

Google tag (gtag.js)