Python Lists

Lists are ordered, mutable collections of items. They are one of the most commonly used data types in Python for storing sequences of elements. Lists can contain items of different data types.

Creating Lists

You can create a list by placing comma-separated values inside square brackets.

Tutorials dojo strip

Lists can store multiple items in a single variable. They can include different data types such as strings, integers, floats, and even other lists.

Python

Accessing List Items

You can access individual items in a list using indexing. Python uses zero-based indexing.

The index 0 accesses the first item in the list, while the index -1 accesses the last item.

Python

Modifying List Items

Lists are mutable, meaning you can change their items after creation.

You can modify items by accessing them using their index.

Python

Adding Items to a List

You can add items to a list using the append() method, insert() method, or the extend() method.

  • append() adds an item to the end of the list.
  • insert() adds an item at a specified position.
  • extend() adds multiple items to the end of the list.
Python

Removing Items from a List

You can remove items from a list using the remove() method, pop() method, or the del statement.

  • remove() removes the first occurrence of a specified value.
  • pop() removes an item at a specified index and returns it.
  • del statement removes an item at a specified index.
Python

List Methods

Python provides several built-in methods for list manipulation.

  • len(): Returns the number of items in a list.
  • sort(): Sorts the items in a list in ascending order.
  • reverse(): Reverses the order of items in a list.
Python

Python Lists Example Code

This program creates a list of fruits and demonstrates adding, modifying, removing items, and using list methods.

Python




Python Labs

Tutorials dojo strip