Python slice notationPlease tell me

Asked 2 years ago, Updated 2 years ago, 95 views

I heard that it's very comfortable to use notation, but it's hard to learn. I'm not sure yet, but can you give me an example?

list python slice

2022-09-22 22:36

1 Answers

The slice can be written in the format start:stop[:step]. Where [:step] means that you can use it or not.

If step is not specified

If you write the step value,

When specifying step, pay attention to :end end means that end will not be included starting with end, which does not necessarily mean that end will be included.

Also, if start or end is negative, it means to count from the end of the list.

I'll show you an example

a = [10,11,12,13,14,15,16,17,18,19]

print "a =", a
print "a[0:1]:", a[0:1]
print "a[0:1]:", a[0:10]
print "a[0:1]:", a[0:20]
print "a[0:1]:", a[0:10:2]
print "a[0:1]:", a[:-2]
print "a[0:1]:", a[:-30]

The results are

a = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
a[0:1]: [10]
a[0:1]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
a[0:1]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
a[0:1]: [10, 12, 14, 16, 18]
a[0:1]: [10, 11, 12, 13, 14, 15, 16, 17]
a[0:1]: []

This is.

For more information, see here


2022-09-22 22:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.