TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Slice a List in Python Programs
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython ExamplesPython Tutorials

How to Slice a List in Python Programs

Last updated: Jun 03, 2024 10:52 pm
By Harsh S.
Share
9 Min Read
How to slice a list in python
SHARE

Python list slicing is a powerful and flexible technique for working with lists. Slicing allows you to create new lists by extracting portions of an existing list. In this tutorial, we will explore the basics of list slicing, step by step, with various examples, including both numbers and strings.

Contents
Introduction to ListsBasic List SlicingPython List Slicing SyntaxSlicing with Negative IndicesSlicing with StepsUse Slicing to Modify ListsCommon List Slicing TipsThe 6 Best Python List Slicing ExamplesProblem#1: Reversing a ListProblem#2: Extracting a SublistProblem#3: Removing DuplicatesProblem#4: Find Middle ElementProblem#5: Replace Element in RangeProblem#6: Palindromic SubstringsBefore You Leave

Understand How Slicing Works in Python

One of the main reasons for Python to have list slicing is to make it easier to work with lists.

Before list slicing, there were only a few ways to access elements of a list, such as using indexing or iteration. List slicing provides a more concise and efficient way to access and modify sublists.

Try Yourself: The Best 30 Questions on Python List, Tuple, and Dictionary

How list slicing works in python

Sometimes, we might have to see if a Python list contains elements of another list or not. There are many such logical use cases we have to take care of as a programmer.

Introduction to Lists

Before we dive into list slicing, let’s quickly review what lists are. Lists are ordered collections of items in Python.

They can contain various data types, including integers, strings, or even other lists. Lists are defined using square brackets [], with elements separated by commas.

my_list = [7, 12, 3, 9, 5, "apple", "banana", "cherry"]

Basic List Slicing

List slicing allows you to extract a subset of elements from a list. To perform basic list slicing in Python, you need the list and two indices: the start and end positions.

Also Read: Python List Sort Method

my_list = [7, 12, 3, 9, 5, "apple", "banana", "cherry"]
subset = my_list[1:5]
print(subset)

This code will print: [12, 3, 9, 5]

The start index is inclusive, and the end index is exclusive. So, the range [1:5] includes elements at index 1, 2, 3, and 4, but not 5.

Python List Slicing Syntax

List slicing syntax in python

The syntax for list slicing is as follows:

new_list = original_list[start:end]
  • start: The index of the first element you want to include.
  • end: The index of the first element you want to exclude.

Slicing with Negative Indices

You can also use negative indices for slicing. Firstly, there is no zero index in negative indices. Secondly, they count from the end of the list.

It means the last value is at -1, the second last is at -2, and so on. However, even with -ve indexing, the starting element (at -3 index) is inclusive whereas the last one is exclusive. This logic is similar to the basic slicing case. Here is the -ve Python list slicing example followed by its pictorial representation.

my_list = [7, 12, 3, 9, 5, "apple", "banana", "cherry"]
subset = my_list[-3:-1]
print(subset)

This code will print: ["apple", "banana"]

Negative list slicing in python

Slicing with Steps

You can also include an optional third parameter in Python list slicing, which defines the step size. This tells you how many elements to leave between each element.

my_list = [7, 12, 3, 9, 5, "apple", "banana", "cherry"]
subset = my_list[0:8:2]
print(subset)

This code will print: [7, 3, 5, "banana"]

In this example, the step size is 2, which means we’re skipping every second element from the list. Below is a picture depicting the list-slicing flow with steps.

optional third step parameter

Use Slicing to Modify Lists

List slicing can also be used to modify the original list. For example, you can replace a portion of a list with new values.

my_list = [7, 12, 3, 9, 5, "apple", "banana", "cherry"]
my_list[1:5] = ["orange", "grape", "pear", "strawberry"]
print(my_list)

This code will print: [7, "orange", "grape", "pear", "strawberry", "apple", "banana", "cherry"]

Common List Slicing Tips

Here are some common list-slicing techniques with examples:

Sr.PurposeHow To
1.Copy a Python ListTo create a copy of a Python list, you can use this:
new_list = original_list[:]
2.Reverse a Python ListTo reverse a list in Python, use this:
reversed_list = original_list[::-1].
3.Get the First N ElementsTo get the first N elements, use this:
subset = my_list[:3].
4.Get the Last N ElementsTo get the last N elements of a list, use this:
subset = my_list[-2:].
5.Remove ElementsTo remove elements from a list, you can use slicing.
6.Splitting ListsYou can split a list into smaller lists using slicing.
Python Slicing Tips

The 6 Best Python List Slicing Examples

List slicing is a core concept in Python and surfaces in various programming challenges. Here are the 6 best list-slicing problems along with their descriptions and sample Python code solutions.

Problem#1: Reversing a List

Description: Given a list, reverse it using list slicing.

Code:

lst = [1, 2, 3, 4, 5]
rev_lst = lst[::-1]
print(rev_lst)

Problem#2: Extracting a Sublist

Description: Given a list, extract a sublist that contains elements within a specified range.

Code:

lst = [10, 20, 30, 40, 50, 60]
sub = lst[2:5]  # Extract elements at indices 2, 3, and 4
print(sub)

Problem#3: Removing Duplicates

Description: Given a list with duplicate elements, remove duplicates using list slicing.

Code:

lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))  # Using set to remove duplicates, then converting back to a list
print(unique)

Also Check: Python Program to Convert Lists into a Dictionary

Problem#4: Find Middle Element

Description: Given a list, find the middle element(s), or elements if the list has an even length.

Code:

lst = [1, 2, 3, 4, 5, 6]
mid = lst[len(lst) // 2]  # For odd-length lists
print(mid)
mid_elements = lst[(len(lst) - 1) // 2:(len(lst) + 2) // 2]  # For even-length lists
print(mid_elements)

Problem#5: Replace Element in Range

Description: Given a list, replace elements in a specified range with new values.

Code:

lst = [10, 20, 30, 40, 50]
lst[1:4] = [25, 35, 45]  # Replace elements at indices 1, 2, and 3
print(lst)

Also Check: Find All Possible Permutation of a String in Python

Problem#6: Palindromic Substrings

Description: Given a string, find all palindromic substrings using list slicing.

Code:

def find_palindromic_subs(s):
    subs = [s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)]
    pals = [sub for sub in subs if sub == sub[::-1]]
    return pals

input_str = "abcbamadam"
pal_subs = find_palindromic_subs(input_str)
print(pal_subs)

These examples use shorter variable and function names while maintaining clarity and readability.

Before You Leave

That’s it! You’ve learned the basics of Python list slicing, including various examples with both numbers and strings. Slicing is a versatile tool for working with lists, and with practice, you’ll become proficient in using it for various tasks.

List slicing allows programmers to perform a variety of complex tasks on lists with just a few lines of code. This makes Python a very attractive language for data science and machine learning applications.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Happy coding,
TechBeamers.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Python Ord() Function Python Ord() Function All You Need to Know
Next Article Python Nested Lists with Examples How to Use Nested Lists in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x