TUTORIAL - Python List (Complete A to Z)

By YBI Foundation

CONTENTS

1. Introduction

2. Creating List

3. List Indexing

​Introduction

Python list is highly versatile data structure that allows you to store an ordered collection of heterogenous items. 

Think of it as a container that can hold various types of data, including numbers, strings, and even other lists. What makes lists particularly powerful is their mutability, meaning you can modify them after creation by adding, removing, or changing elements.

These ordered sequences are defined by enclosing comma-separated items within square brackets, and each item within a list is assigned an index, beginning with zero, which enables you to access and manipulate individual elements efficiently.

my_list = [ 1, 2, 1.2, 'ybi foundation, True]

​Creating List

Creating lists in Python is a straightforward process. The most common way is to enclose a comma-separated sequence of items within square brackets [ ]. This allows you to directly initialize a list with specific values, whether they are numbers, strings, or a mix of data types. 

For instance, my_list = [1, "hello", 3.14] creates a list containing an integer, a string, and a float. 

Alternatively, you can create an empty list using my_list = [ ] and then add elements later using methods like append() or insert(). 

Another powerful technique is to use the list() constructor, which can convert other iterable data types, such as tuples or strings, into lists. 

LIST INDEXING

​List Indexing

List indexing in Python refers to the process of accessing individual elements within a list by their position. Here's a breakdown of the key concepts:
Zero-Based Indexing:
Python lists use zero-based indexing, meaning the first element in a list has an index of 0, the second element has an index of 1, and so on.
Accessing Elements:
You access list elements using square brackets [] and the index number. For example, my_list[0] retrieves the first element of the list my_list.
Negative Indexing:
Python also supports negative indexing, which allows you to access elements from the end of the list.
my_list[-1] retrieves the last element, my_list[-2] retrieves the second-to-last element, and so on.
Slicing:
In addition to accessing individual elements, you can also extract a portion of a list using slicing.
Slicing uses the syntax my_list[start:stop:step], where:
start is the index of the first element to include (inclusive).
stop is the index of the first element to exclude (exclusive).
step is the increment between elements.
IndexError:
If you try to access an index that is outside the range of valid indices for a list, Python will raise an IndexError.
LIST METHODS

List Methods

In Python, lists are one of the most versatile and commonly used data structures. They come with a variety of built-in methods and functions that allow you to manipulate and interact with the data they contain. Below is a list of commonly used list methods and functions:

1. append(item): Adds an item to the end of the list.
​Code </>:
​# adds `5` to the end of `my_list`.​
my_list.append(5)

Output:


1. append(item): Adds an item to the end of the list.
​Code </>:
​# adds `5` to the end of `my_list`.​
my_list.append(5)

Output:


2. extend(iterable):  Adds all elements of an iterable (e.g., list, tuple, string) to the end of the list.

Code </>:

# adds 1, 2, 3 to the end of my_list

my_list.extend([1, 2, 3])

Output:


3. insert(index, item):  Inserts an item at a specified index.

Code </>:

#  inserts 'x' at index 1

my_list.insert(1, 'x')

Output:


4. remove(item): Removes the first occurrence of the specified item.

Code </>:

# removes the first 'x' from my_list

my_list.remove('x') 

Output:


5. pop([index]): Removes and returns the item at the specified index. If no index is specified, it removes and returns the last item.

Code </>:

# removes and returns the item at index 1

my_list.pop(1)

Output:


6. clear(): Removes all items from the list.

Code </>:

# empties the list

my_list.clear()

Output:


7. index(item[, start[, end]]): Returns the index of the first occurrence of the specified item. You can specify a start and end index to search within a sublist.

Code </>:

returns the index of the first 'x'

my_list.index('x')

Output:


8. count(item): Returns the number of times the specified item appears in the list.

Code </>:

returns the count of 'x' in my_list

my_list.count('x')

Output:


9. sort(key=None, reverse="False): Sorts the list in place. You can specify a key function for custom sorting and a reverse flag to sort in descending order.

Code </>:

sorts the list in descending order

my_list.sort(reverse=True)

Output:


10. reverse(): Reverses the elements of the list in place.

Code </>:

reverses the order of elements in my_list

my_list.reverse()

Output:


11. copy(): Returns a shallow copy of the list.

Code </>:

creates a copy of my_list

new_list = my_list.copy()

Output:


LIST FUNCTIONS

List Functions

These are built-in Python functions that can operate on lists (among other iterables). They are general-purpose functions, not tied specifically to list objects.
1. len(list): Returns the number of items in the list.

Code </>:

returns the length of my_list

len(my_list)

Output:


2. min(list): Returns the smallest item in the list.

Code </>:

returns the smallest element in my_list

min(my_list)

Output:


3. max(list): Returns the largest item in the list.

Code </>:

returns the largest element in my_list

max(my_list)

Output:


4. sum(list): Returns the sum of all items in the list (only for numeric lists).

Code </>:

returns the sum of all elements in my_list

sum(my_list)

Output:


5. sorted(list, key=None, reverse= False): Returns a new sorted list from the elements of the list. The original list remains unchanged.

Code </>:

 returns a new list sorted in descending order

sorted(my_list, reverse=True)

Output:


6. any(list): Returns True if at least one element in the list is True (or truthy).

Code </>:

 returns True if any element in my_list is True

any(my_list)

Output:


7. all(list): Returns True if all elements in the list are True (or truthy).

Code </>:

 returns True if all elements in my_list are True

all(my_list)

Output:


8. list(iterable): Converts an iterable (e.g., tuple, string, set) into a list.

Code </>:

 converts the string 'hello' into ['h', 'e', 'l', 'l', 'o']

list('hello')

Output:


EXAMPLES

Examples

# Example list
my_list = [3, 1, 4, 1, 5, 9]
# Append
my_list.append(2)  # [3, 1, 4, 1, 5, 9, 2]
# Extend
my_list.extend([6, 5])  # [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Insert
my_list.insert(2, 'x')  # [3, 1, 'x', 4, 1, 5, 9, 2, 6, 5]
# Remove
my_list.remove('x')  # [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Pop
popped_item = my_list.pop(1)  # popped_item = 1, my_list = [3, 4, 1, 5, 9, 2, 6, 5]
# Clear
my_list.clear()  # []
# Index
my_list = [3, 1, 4, 1, 5, 9]
index = my_list.index(1)  # index = 1
# Count
count = my_list.count(1)  # count = 2
# Sort
my_list.sort()  # [1, 1, 3, 4, 5, 9]
# Reverse
my_list.reverse()  # [9, 5, 4, 3, 1, 1]
# Copy
new_list = my_list.copy()  # new_list = [9, 5, 4, 3, 1, 1]
# Len
length = len(my_list)  # length = 6
# Min
minimum = min(my_list)  # minimum = 1
# Max
maximum = max(my_list)  # maximum = 9
# Sum
total = sum(my_list)  # total = 23
# Sorted
sorted_list = sorted(my_list, reverse="True)"  # sorted_list = [9, 5, 4, 3, 1, 1]
# Any
any_true = any(my_list)  # any_true = True
# All
all_true = all(my_list)  # all_true = True
# List
converted_list = list('hello')  # converted_list = ['h', 'e', 'l', 'l', 'o']