How to slice variable in python

Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation. For example, the slice assignment list[2:4] = [42, 42] replaces the list elements with index 2 and 3 with the value 42.

>>> lst = [1, 2, 3, 4, 5]
>>> # Slicing
>>> lst[2:4]
[3, 4]
>>> # Slice Assignment
>>> lst[2:4] = ['Alice', 'Bob']
>>> lst
[1, 2, 'Alice', 'Bob', 5]
>>> lst[2:4]
['Alice', 'Bob']

I’ve recorded a quick video that shows you how the slice assignment feature works in a Python One-Liner:

Python One-Liners - Trick 6 - Slice Assignment to Clean Corrupted Browser Data

Play With Slice Assignment in Your Interactive Shell

How to slice variable in python

Before I’ll explain it to you, feel free to play with this feature yourself:

One of my Finxter users, Mike, asked the following great question:

“I was going through a lot of slicing puzzles on the Finxter site, I came across this:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[1:] = [ ]
print(letters)

I originally answered [‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’] but got it wrong.”

This is the point where I want to open your knowledge gap: what’s the output of this puzzle instead?

** For your convenience, you can also solve this specific puzzle on the Finxter app here. **

“As the answer is [‘a’], I immediately became curious because that’s [not] the answer if we use this code

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[1:])
# ['b', 'c', 'd', 'e', 'f', 'g']

Why do these work differently?
Thanks, I really appreciate your time and all of the content you provide each day.”

Again, great question. Mike did most of the heavy lifting himself. The answer is simple (if you have read my slicing booklet already):

  • The first version is slice assignment.
  • The second version is basic slicing.

They are not the same. You should not confuse slicing and slice assignment. Here is the difference:

1) Slicingcreates a new subsequence of the original sequence. You can assign this new sequence to a variable y. In essence, you overwrite any previous value of variable y:

x = list("coffeebreak")
y = list("python")

y = x[0:4]
print(''.join(y))
# 'coff'

2) Slice assignment replaces the selected slice in the original sequence y with the value specified on the right-hand side of the equation:

x = list("coffeebreak")
y = list("python")

y[0:2] = x
print(''.join(y))
# 'coffeebreakthon'

Note that the two code snippets also demonstrate how you can convert a string to a list and convert a list back to a string.


This Python lesson is based on my free “Coffee Break Python” Email Series. Join us. It’s fun! ?

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

How to slice variable in python

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Can you slice a variable in python?

Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.

How do you slice in python?

Python slice() Function A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

Can we slice a string in python?

Slicing Strings You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

How do I slice a data list in python?

The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.