开发者

Confusing expression in python

开发者 https://www.devze.com 2023-01-21 07:08 出处:网络
If I have the list: lista=[99, True, \"Una Lista\", [1,3]] What does the f开发者_Python百科ollowing expression mean?

If I have the list:

lista=[99, True, "Una Lista", [1,3]]

What does the f开发者_Python百科ollowing expression mean?

mi_var = lista[0:4:2]


The syntax lista[0:4:2] is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2).

In your example it will give [99, "Una Lista"]. More generally you can get a slice consisting of every element at an even index by writing lista[::2]. This works regardless of the length of the list because the start and end parameters default to 0 and the length of the list respectively.

One interesting feature with slices is that you can also assign to them to modify the original list, or delete a slice to remove the elements from the original list.

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2] = ['a', 'b', 'c', 'd', 'e']   # Assign to index 0, 2, 4, 6, 8
>>> x
['a', 1, 'b', 3, 'c', 5, 'd', 7, 'e', 9]
>>> del x[:5]                            # Remove the first 5 elements
>>> x
[5, 'd', 7, 'e', 9]


Iterate through the list from 0 to 3 (since 4 is excluded, [start, end)) stepping over two elements. The result of this is [99, 'Una Lista'] as expected and that is stored in the list, mi_var


One way just to run and see:

>>> lista=[99, True, "Una Lista", [1,3]]
>>> lista[0:4:2]
[99, 'Una Lista']

It's a slice notation, that creates a new list consisting of every second element of lista starting at index 0 and up to but not including index 4

0

精彩评论

暂无评论...
验证码 换一张
取 消