List in Python

List in Python for beginners

Bhavik Jikadara
2 min readFeb 27, 2024

Here, I will share knowledge about List in Python.

In Python, a list is a fundamental data structure used to store an ordered collection of items. It’s one of the most versatile tools in Python’s arsenal, offering several key features:

  • Ordered: Elements in a list follow a specific sequence, maintained from creation. You can access elements based on their position in the list.
  • Mutable: Unlike some other data structures in Python, lists are mutable, meaning you can modify their contents after creation. You can add, remove, or change elements within the list.
  • Heterogeneous: Unlike some other languages, Python lists are heterogeneous, meaning they can hold elements of different data types. A single list can contain integers, strings, floats, and even other lists, creating nested structures.

Here’s a quick overview of creating, accessing, and manipulating lists in Python:

Creating a List:

# Empty list
my_list = []

# List with elements
fruits = ["apple", "banana", "orange"]

# List with different data types
mixed_list = [10, 3.14, "hello"]

Accessing Elements:

  • Elements are accessed using indexing, starting from 0. The first element has an index of 0, the second has an index of 1, and so on.
  • You can also use negative indexing to access elements from the end. -1 refers to the last element, -2 to the second last, and so on.
print(fruits[1]) # Output: banana
print(mixed_list[-2]) # Output: 3.14

Modifying Lists:

Python offers various methods to modify lists:

  • append(element): Adds an element to the end of the list.
  • insert(index, element): Inserts an element at a specific index.
  • remove(element): Removes the first occurrence of the specified element.
  • pop(index): Removes and returns the element at a specific index (or the last element if no index is provided).

Additional points:

  • You can use the len(list) function to find the number of elements in a list.
  • Slicing allows you to extract a portion of a list based on specified indices.
  • Python provides various built-in methods for common list operations like sorting, searching, and reversing.

--

--

Bhavik Jikadara
Bhavik Jikadara

Written by Bhavik Jikadara

🚀 AI/ML & MLOps expert 🌟 Crafting advanced solutions to speed up data retrieval 📊 and enhance ML model lifecycles. buymeacoffee.com/bhavikjikadara

No responses yet