Working with Python Lists: Accessing, Creating & Deleting

Python Python Basics

Python lists are a fundamental data structure that can be used to store collections of items. In this article, we will explore the various ways you can create, access, iterate through, search, delete elements, and extend Python lists.

Table of Contents

Creating Lists

You can create a list in Python using square brackets []. Here’s an example:

my_list = [1, 2, 3, "strawberry", "lime"]


[1, 2, 3, 'strawberry', 'lime']

Accessing List Elements

You can access elements in a list using their index. Python uses zero-based indexing, so the first element has an index of 0. For example:

my_list = [1, 2, 3, "strawberry", "lime"]
print(my_list[0]) # Output: 1
print(my_list[4]) # Output: lime

Iterating through Lists

You can iterate through a list using a for loop. This is a common way to process each element in a list.

my_list = [1, 2, 3, "strawberry", "lime"]
for item in my_list:



Searching for Elements in Lists

You can search for an element in a list using the in keyword. This returns a boolean value indicating whether the item exists or not.

my_list = [1, 2, 3, "strawberry", "lime"]
print("strawberry" in my_list) # Output: True
print("orange" in my_list) # Output: False

Deleting List Elements

You can remove an item from a list using the remove() method. This will remove the first occurrence of the specified element.

my_list = [1, 2, 3, "strawberry", "lime"]
print(my_list) # Output: [1, 2, 3, 'strawberry']

Extending Lists

You can extend a list by adding new elements using the append() method or the + operator.

my_list = [1, 2, 3]
print(my_list) # Output: [1, 2, 3, 'lime']

my_list += ["strawberry", "orange"]
print(my_list) # Output: [1, 2, 3, 'lime', 'strawberry', 'orange']

To top