Python Lists
Lists in Python
A list is a collection of items that are ordered and mutable (meaning you can modify the elements). Lists can store elements of different types, such as integers, floats, strings, or even other lists.
Key Features of Lists:
- Ordered: The elements in a list have a defined order, and this order will not change unless explicitly modified.
- Mutable: You can change the elements of a list after it is created.
- Heterogeneous: A list can contain elements of different types.
- Dynamic: Lists can grow and shrink as needed.
List Syntax:
To define a list in Python, you use square brackets []
, with elements separated by commas.
Example of Common List Operations
- Creating a List:
- Accessing Elements:
- You can access individual elements using an index (starting from 0).
- Negative Indexing:
- Negative indexing allows you to access elements from the end of the list.
- Slicing a List:
- You can access a portion of the list (called slicing).
- Modifying Elements:
- Since lists are mutable, you can modify an element.
- Adding Elements:
- You can add elements using
append()
,insert()
, orextend()
methods.
- You can add elements using
- Removing Elements:
- Elements can be removed using
remove()
,pop()
, ordel
.
- Elements can be removed using
- Checking Length of List:
- You can find the number of elements in a list using
len()
.
- You can find the number of elements in a list using
- Looping Through a List:
- You can loop over the elements in a list using a
for
loop.
- You can loop over the elements in a list using a
- List Comprehension:
- List comprehension is a concise way to create a new list by iterating over an existing list.
More List Methods:
sort()
: Sorts the list in ascending order.reverse()
: Reverses the list.index()
: Returns the index of the first matched element.count()
: Returns the number of occurrences of a value.
Summary:
- A list is a versatile, mutable data structure that allows you to store a collection of ordered elements.
- It can handle different data types and supports a variety of operations like adding, removing, and modifying elements.