How to Slice Up Lists in Python - The Camel Cock Vendor

in #python6 years ago (edited)

Who likes Chinese food? Fucking no one likes Chinese food except for Chinese people. I do however enjoy the warped abomination Americans call Chinese food that has zero resemblance to its namesake.

For more NSFW Python 3 tutorials, visit Redheadedpython.com

Lets say you wake up and you’re magically in China. I hope you speak Mandarin and have a taste for dogs and cats.

Because you’re a normal person who eats food shortly after waking up, you decide to go to the market. More bad news. You didn’t even wake up in a good city in China. You woke up in some random shithole city in the middle of a Chinese desert. The only thing the locals are serving is hard decapitated camel schlong.

As the camel schlong vendor is about to sell you his best, you realize you have no money. Therefore, you decide to teach him how to slice arrays. First, you grab 4 camel wangs (the term wang seems oddly more appropriate for China). You explain how to count the elements. But lets say you only want to buy the first 3 camel wangs in his list…

You would do it like this:

The middle two wangs wouldbe like [1:2]. So on and so forth. Lets the camel wang vendor has dozens of wangs to sell you and you just want the last one on that list. You don’t want to count how many wangs and specify the last one… good thing you can specify the last element like this:

Or you can specify the last 3 wangs:

Note how it is left empty after the colon. That means to keep going until the end. Same goes for [:5]. That is the same as [0:5]. That’s the lazy way to say you want to eat those first 5 delicious camel wangs. You tell Wang you want those wangs and enjoy the rest of your trip along the Great Firewall of China.