Python Lists (List)
Lists are one of the most fundamental and commonly used data structures in Python. They are ordered and mutable collections that can contain objects of any type.
Creating Lists
Lists are defined using square brackets [], with elements separated by commas ,.
Accessing List Elements
Just like strings, you can access list elements through indexing and slicing.
Indexing
Slicing
Lists are Mutable
Unlike strings and tuples, lists are mutable. This means you can modify, add, and remove elements from the list.
Common List Methods
Python provides many built-in methods for lists.
list.append(x): Adds an elementxat the end of the list.list.insert(i, x): Inserts an elementxat the specified positioni.list.extend(iterable): Adds all elements from an iterable (such as another list) to the end of the list.list.remove(x): Removes the first element with valuexfrom the list.list.pop(i): Removes and returns the element at the specified positioni. If no index is specified, removes and returns the last element.list.clear(): Removes all elements from the list.list.index(x): Returns the index of the first element with valuexin the list.list.count(x): Returns the number of times elementxappears in the list.list.sort(): Sorts the list in place (modifies the original list).list.reverse(): Reverses the elements in the list in place.list.copy(): Returns a shallow copy of the list.
Example:
List Operations
- Concatenation: Using the
+operator to concatenate two lists creates a new list. - Repetition: Using the
*operator to repeat list elements.