GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Books
  • Mini
  • Tips
  • Tags
  • About
  • learnbyexample

This view

  • Original page
  • New address

GeezerVison is showing learnbyexample.github.io — Python tip 24: modifying list using insert and slice

The insert() list method helps to insert an object before the given index. Negative indexing is also supported.

>>> books = ['Sourdough', 'Sherlock Holmes', 'Cradle']

# same as: books.insert(-1, 'The Martian')
>>> books.insert(2, 'The Martian')
>>> books
['Sourdough', 'Sherlock Holmes', 'The Martian', 'Cradle']

# index >= list-length will append the object at the end
>>> books.insert(1000, 'Legends & Lattes')
>>> books
['Sourdough', 'Sherlock Holmes', 'The Martian', 'Cradle', 'Legends & Lattes']

You can use slicing notation to modify one or more list elements. The list will automatically shrink or expand as needed. Here are some examples:

>>> nums = [1, 4, 6, 22, 3, 5]

# modify a single element
>>> nums[0] = 100
>>> nums
[100, 4, 6, 22, 3, 5]

# modify the last three elements
>>> nums[-3:] = [-1, -2, -3]
>>> nums
[100, 4, 6, -1, -2, -3]

# elements at index 1, 2 and 3 are replaced with a single object
>>> nums[1:4] = [2000]
>>> nums
[100, 2000, -2, -3]

# element at index 1 is replaced with multiple elements
>>> nums[1:2] = [3.14, 4.13, 6.78]
>>> nums
[100, 3.14, 4.13, 6.78, -2, -3]

info RHS must be an iterable when you use slicing notation with :, even when LHS refers to a single element. For example, nums[1:2] = 100 is not valid.

Video demo:


info See also my 100 Page Python Intro ebook.

#python#tip

← Python tip 25: split and partition string methods

Python tip 23: map, filter and reduce →


📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.