Create an array w with values 0, 0.1, 0.2, . . . , 3. Write out w[:], w[:-2], w[::5], w[2:-2:6]. Convince yourself in each case that you understand which elements of the array that are printed.

Respuesta :

Answer:

w = [i/10.0 for i in range(0,31,1)]

w[:]  = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0]

w[:-2] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8]

w[::5]= [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]

w[2:-2:6] = [0.2, 0.8, 1.4, 2.0, 2.6]

Explanation:

List slicing (as it is called in python programming language ) is the creation of list by defining  start, stop, and step parameters.

w = [i/10.0 for i in range(0,31,1)]

The line of code above create the list w with values 0, 0.1, 0.2, . . . , 3.

w[:]  = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0]

since start, stop, and step parameters are not defined, the output returns all the list elements.

w[:-2] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8]

w[:-2] since  stop is -2, the output returns all the list elements from the beginning to just before the second to the last element.

w[::5]= [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]

w[::5] since  step is -2, the output returns  the list elements at index 0, 5, 10, 15, 20, 25,30

w[2:-2:6] = [0.2, 0.8, 1.4, 2.0, 2.6]

the output returns the list elements from the element at index 2  to just before the second to the last element, using step size of 6.