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

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




Accessing List Items

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

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




Modifying List Items

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

Explanation: You can modify items by accessing them using their index.




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.




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.




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 Lists Example Code

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




Python Labs

Tutorials dojo strip