DEV Community

Katana Tran
Katana Tran

Posted on

Learning a bit about Python: A quicker way to slice

Introduction

I recently started learning Python as an alternative to using Javascript for coding algorithms. What I noticed is Python had a different toolkit than I was used to in Ruby and JS, particularly for array/list methods.

Here are a few tricks I've learned and hopefully they'll be helpful to you too!

Descriptions

Lists: Lists are akin to arrays, they follow the square bracket notation and are mutable.

list = [1,2,3,4,5]

Tuples:

  • Tuples take the same structure as lists but are immutable, this means they cannot be changed to represent a new value after creation.
  • Tuples are represented by parentheses.
  • They make debugging easier, since you know the information will remain unchanged through a tuple, you can mitigate tracking of past edits.
  • Modification of tuples can work such as iterating and adding extra indices to the tuple, but this requires a longer run time than if you used a list since the tuple must be remade each iteration and the old ones destroyed.

tuple = (1,2,3,4,5)

Methods to use

Think about the times you had to do the following.

  • Reversing a list?
  • Slicing a list?
  • Grab only even or odd numbers from an array?

Python allows us a great tool to better grab such information from a list, tuple, or even a string!

object[start:stop:step]

What you want to slice can be sliced with this simple format. Pick what index to start, which to stop (not including this index), and how many steps in between new indexes. If you leave the start empty, it will start at the beginning of the array, leave the stop empty, it'll end at the end of the array. Step is automatically 1 unless otherwise specified.

Imagine a string and a list

bob = "Bob loves bananas!"

numbers = [1,2,3,4,5,6,7,8,9,10]

This would be how to use the above tool to gather what I need in each scenario:

  • I only want bob's name: bob[:3]
  • I want to reverse the numbers: numbers[::-1]
  • I also want to reverse what bob loves:

bobloves = bob[-8:-1]
bobloves[::-1]

  • I only want odd numbers: numbers[::2]
  • I want a slice of numbers from 1-9: numbers[:-1]
  • I want a slice of numbers from 5-10: numbers[4:]
  • I want a slice of numbers from 2-9: numbers[1:-1]

This is much quicker for me than creating a new slice object in Python then applying that to the array I need to slice. (This can be great for other reasons of course.)

This was my first Dev.to post and I am excited to continue sharing with the community and learning more from everyone!

Top comments (1)

Collapse
 
monical2183 profile image
monical2183

Great content easy to understand for someone like me that's a beginner. Thanks for sharing