Introduction to Python
  • Introduction
  • Preface
  • Background
  • Installing Python
  • Getting Started
  • Basics
    • More Printing
    • Strings
    • Numbers
    • Exercises
    • Comments
  • Variables
    • Operators
    • Type Conversion
    • Exercises
    • A Brief Introduction to Lists
    • Game Exercise
  • Human Input
  • Functions
    • First Functions
    • Why Functions
    • Exercises
  • Indentation
  • Decisions
    • Booleans
    • Logical Operators
    • If Statements
    • Elif and Else Statements
    • Exercises
    • Rock, Paper, Scissors
    • Game Exercise
    • Game Exercise 2
  • Lists
  • Loops
    • For Loops
    • While Loops
  • More Data Structures
    • Tuples
    • Dictionaries
  • Pygame
  • Extra Content
    • Computers and Code
    • More About Python
    • For Loops with Range
    • List Slicing
Powered by GitBook
On this page
  1. Extra Content

List Slicing

Slicing is taking a portion of a list and creating a new one. Think of it like cutting a slice of cake, but the original one stays intact (wouldn't that be absolutely amazing?). Let's see below:

fruits = ['banana', 'mango', 'tomato', 'plum', 'guava']
fruits[1] # 'mango'

# Let's slice to get a new list that starts from mango
fruits[1:]
# Above we tell Python we want a list that starts from the fruit's second item
# (recall that the 2nd item has index 1) till the end of the list

# So if we wanted plum and guava chow (ewww) we'll do the following
fruits[3:]

# Let's slice to get a new list that ends with plum
fruits[:4]
# Above we tell Python to start slicing from the beginning and end with fruit's
# 4th item. It's a little tricky, when a number came before the colon we gave
# the item's index. Now we give one more than the item's index. Practice more!
fruits[:5] # ['banana', 'mango', 'tomato', 'plum', 'guava']
fruits[:1] # ['banana']
fruits[:3] # ['banana', 'mango', 'tomato']

# Let's take it a step further and put them both together
fruits[1:4] # ['mango', 'tomato', 'plum']
# Make sure you understand, you're skipping the first element and going up to
# the fourth one. Skip banana and stop and plum
fruits[2:3] # Skip banana and mango, end at tomato. So only tomato!
PreviousFor Loops with Range

Last updated 6 years ago