techmore.in

Python - Lists

Lists in Python are used to store multiple items in a single variable. They are one of Python's most flexible data structures.

Creating a List

You can create a list by placing elements inside square brackets [].

python
my_list = [1, 2, 3, 4, 5] print(my_list)

List Indexing and Slicing

Lists are ordered and indexable. Index starts from 0.

python
print(my_list[0]) # First element print(my_list[-1]) # Last element print(my_list[1:4]) # Slice from index 1 to 3

List Methods

Python provides several built-in methods to manipulate lists.

python
my_list.append(6) my_list.insert(0, 0) my_list.remove(3) my_list.pop() my_list.sort() my_list.reverse() print(my_list)

Looping Through Lists

You can use loops to iterate through list elements.

python
for item in my_list: print(item)

List Comprehension

A concise way to create lists in Python.

python
squares = [x**2 for x in range(10)] print(squares)

Nested Lists

Lists can contain other lists as elements.

python
nested = [[1, 2], [3, 4], [5, 6]] print(nested[0][1]) # Output: 2

Pros and Cons of Python Lists

Pros:

  • Dynamic sizing
  • Heterogeneous data types allowed
  • Powerful built-in methods

Cons:

  • Slower than arrays for large data (use NumPy)
  • Memory overhead