HOME HTML EDITOR C JAVA PHP python

Python Lists

A list in Python is an ordered, mutable (changeable) collection enclosed in square brackets ([]). Lists allow duplicate elements and can store items of mixed data types.

Creating, Indexing, and Slicing Lists

List items are zero-indexed, support negative indexing from the end, and can be sliced using [start:stop]:

fruits = ["apple", "banana", "cherry", "mango"]

print(fruits[0])      # apple
print(fruits[-1])     # mango
print(fruits[1:3])    # ['banana', 'cherry']
print(len(fruits))    # 4

Modifying and Common List Methods

  • Change Item: Assign a new value by index, such as fruits[1] = "orange".
  • append(item): Adds an item to the end of the list.
  • insert(index, item): Inserts an item at a specific position.
  • remove(value) & pop(): Removes a matching value or removes an item by index (default is the last item).
tasks = ["code", "test"]

tasks.append("deploy")        # ['code', 'test', 'deploy']
tasks.insert(1, "review")     # ['code', 'review', 'test', 'deploy']
tasks.remove("test")          # ['code', 'review', 'deploy']
last_task = tasks.pop()       # removes 'deploy'

print(tasks)
print(last_task)
Tip: Lists preserve insertion order and allow duplicates—if you need unique items without duplicates, look into sets or dictionaries.