If I have the following list: my_list = [1, 2, 3]
. How can I take all the elements using slice()
built-in method without knowing the length of my_list
?
my_list[slice(-1)]
gives me [1, 2]
and my_list[slice(':')]
gives me a TypeError.
Is there something similar to my_list[:]
that I can use with slice so that I can define a variable before the list is created?
You can pass None
>>> my_list = [1, 2, 3]
>>> id(my_list)
1827682884416
>>> copy = my_list[slice(None)]
>>> id(copy)
1827682861888
>>> copy
[1, 2, 3]
>>> my_list is copy
False
I believe that my_list[:]
is just a syntactic sugar. You can confirm this by dis
module.
>>> import dis
>>> dis.dis("my_list[:]")
1 0 LOAD_NAME 0 (my_list)
2 LOAD_CONST 0 (None)
4 LOAD_CONST 0 (None)
6 BUILD_SLICE 2
8 BINARY_SUBSCR
10 RETURN_VALUE
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.