Computer Science
If a is [1, 2, 3]
- what is the difference (if any) between a * 3 and [a, a, a]?
- is a * 3 equivalent to a + a + a?
- what is the meaning of a[1:1] = 9?
- what's the difference between a[1:2] = 4 and a[1:1] = 4?
Answer
- 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. - Yes, both a * 3 and a + a + a will result in [1, 2, 3, 1, 2, 3, 1, 2, 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.
- 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].
Related Questions
Start with the list [8, 9, 10]. Do the following using list functions:
- Set the second entry (index 1) to 17
- Add 4, 5 and 6 to the end of the list
- Remove the first entry from the list
- Sort the list
- Double the list
- Insert 25 at index 3
How are the statements lst = lst + 3 and lst += [3] different, where lst is a list? Explain.
What do you understand by mutability? What does "in place" memory updation mean?
What's a[1 : 1] if a is a list of at least two elements? And what if the list is shorter?