How to Slice a List in Python

Save

A list in Python is a compound data type that's most akin to an array. Multiple values are stored in a particular order in a list, and are referenced via a number called an index. Slicing a list means creating a new list containing copies of some subset of the values in the list being sliced. Slice a list by specifying the index values at the beginning and end of the subset you want to slice.

  • Launch the Python command line interpreter.

  • Create a list with the following command:

    list = ['a','b','c',1,2,3,'item 1','item 2','item 3']

    View the contents of the list at any time by typing its name -- "list" -- and pressing "Enter." Note that a single list can contain multiple data types and even other lists.

  • Slice the first three items from the list with the following command:

    list[0:3]

    The slicing occurs on the left sides of the items specified by the indices, and Python indexing starts at "0." In this example, the slicing begins before the first item which has the index value "0," and ends before the fourth item which has the index value "3." The sliced items are not stored, and the original list is not affected -- verify this by typing the command "list." To store the slice, simply assign it to a new variable:

    list2 = list[0:3]

  • Omit index values to capture as many elements as reside to either side of a slice. For example, use the following command to slice every value from the third element to the end of the list:

    list[2:]

    Slice the entire list by omitting both indices:

    list[:]

    This is a good way to make a copy of a list.

  • Use negative indices to reference the list from its end. This may be appropriate for some algorithmic strategies. The last element of a list is indexed by the value "-1." The following command slices the third-to-last and second-to-last items from the list:

    list[-3:-1]

Tips & Warnings

  • Strings are a type of list in Python, and can be sliced using the same syntax.

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!