DEV Community

Josh Stephens
Josh Stephens

Posted on

A different way to slice in python

A very interesting topic came up in my local community slack channel. Someone asked how to do slicing using an object. At first I wasn't sure what they were talking about and why wouldn't the following work for them.

mylist[:5]
Enter fullscreen mode Exit fullscreen mode

After a quick search someone found this reference in the python docs. Which was a good read but I still couldn't quite grasp why. Then it hit me. I remember C having something called macros and I was like oh hey a cool and shorten way to build a slice macro.

So for example you could have

SL5 = slice(5)

my_new_list = my_list[SL5]
my_other_new_list = my_other_list[SL5]

Enter fullscreen mode Exit fullscreen mode

and now we created two new lists with the first five items in my_list and my_other_list. I still haven't found all the ways that this could be useful but I was pretty happy with how I was able to see a new concept and within a few minutes find a good use for it.

PS. sorry for the rough post. This is my first real post on here besides my intro. Content creation is still my weak spot.

Top comments (0)