KnowledgeBoat Logo

Computer Science

If a is [1, 2, 3]

  1. what is the difference (if any) between a * 3 and [a, a, a]?
  2. is a * 3 equivalent to a + a + a?
  3. what is the meaning of a[1:1] = 9?
  4. what's the difference between a[1:2] = 4 and a[1:1] = 4?

Python List Manipulation

60 Likes

Answer

  1. a * 3 ⇒ [1, 2, 3, 1, 2, 3, 1, 2, 3]
    [a, a, a] ⇒ [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    So, a * 3 repeats the elements of the list whereas [a, a, a] creates nested list.
  2. Yes, both a * 3 and a + a + a will result in [1, 2, 3, 1, 2, 3, 1, 2, 3]
  3. a[1:1] = 9 will cause an error because when list is modified using slices, the value being assigned must be a sequence but 9 is an integer not a sequence.
  4. Both a[1:2] = 4 and a[1:1] = 4 will cause error because when list is modified using slices, the value being assigned must be a sequence but 4 is an integer not a sequence. Assuming the question was a[1:2] = [4] and a[1:1] = [4], a[1:2] = [4] will change element at index 1 to 4 as a[1:2] gives a slice with a[1] as its only element. Thus, a becomes [1, 4, 3]. Coming to a[1:1] = [4], a[1:1] returns an empty slice so 4 is inserted into the list at index 1. Thus, a becomes [1, 4, 2, 3].

Answered By

28 Likes


Related Questions