Python Lists

To hold collections of data, Python has a flexible built-in data structure called a list. Lists are structured groups of stuff.
Mutability changing a list’s contents after creation is essential. Lists can dynamically expand or contract as needed and can hold items of several data kinds, making them heterogeneous. Additionally, lists may have duplicate members.
List Basics
Creating
Items in lists are separated by commas and enclosed in square brackets []. [] generates an empty list. The built-in list() function can also be used to generate a list or convert other iterables (such as strings or tuples) into a list. An empty list is produced, for example, by using x = list(). Additionally, a tuple can be converted into a list or its list form obtained using the list() method. The split() method of a string can also be used to construct a list by splitting the string into a list of substrings according to a separator.
# Creating an empty list
my list = []
print(f" Empty list: {my list}")
# Creating a list with elements of different types
mixed list = [1, "hello", 3.14, True]
print(f" Mixed list: {mixed list}")
Example:
# Creating a list from a string
word list = list("python")
print(f" List from string: {word list}")
# Creating a list from range()
number range list = list(range(5))
print(f" List from range: {number range list}")
# Creating a list using splitlines() - useful for text files
text data = "Line 1\nLine 2\nLine 3"
lines list = text data splitlines()
print(f" List from splitlines: {lines list}") [6]
Indexing
Using indexing, you can retrieve certain items within a list. For the first item, indexes begin at 0. It is possible to count from the end using negative indices, where -1 denotes the final element. For instance, list L’s first item is L. A common issue known as the index off-by-one error occurs when the first element is referenced with index 1 rather than 0.
Example:
# Example list
fruits = ["apple", "banana", "cherry", "date"]
# Accessing the first element (index 0)
first fruit = fruits
print(f" First fruit: {first fruit}")
# Accessing the third element (index 2)
third fruit = fruits
print(f" Third fruit: {third fruit}")
# Accessing the last element (index -1)
last fruit = fruits
print(f" Last fruit: {last fruit}")
# Accessing the second to last element (index -2)
second last fruit = fruits
print(f" Second to last fruit: {second last fruit}")
Slicing
A subsequence of items can be extracted from a list by slicing it. This list includes components from the start index to the finish index, but not the end. [start:] gets items from a certain index to the finish and [:end] gets them from the beginning to an index. A step value can also be included in slicing using the list[begin:end:step] form.
Example:
# Example list
numbers = [8-16]
# Get elements from index 2 up to (but not including) index 6
subset1 = numbers
print(f" Slice [2:6]: {subset1}")
# Get elements from the beginning up to (but not including) index 5
subset2 = numbers[:5]
print(f" Slice [:5]: {subset2}")
# Get elements from index 7 to the end
subset3 = numbers
print(f" Slice [7:]: {subset3}")
# Get a copy of the whole list using slicing
copy list = numbers
print(f" Slice [:]: {copy list}")
# Get elements with a step of 2
subset4 = numbers
print(f" Slice [1:9:2]: {subset4}")
# Reverse the list using slicing with a step of -1
reversed list = numbers
print(f" Slice [::-1] (reversed): {reversed list}")
Modifying Lists
Adding, Changing, Deleting, and Removing Elements. Lists can have their contents altered in real time since they are mutable. One significant distinction between lists and strings is that whereas list methods alter the original list, string methods do not alter the original string.
Adding Elements: Adding an item x to the end of the list is done with append(x). This method of creating a list from scratch is widely used.
- Insert(i, x) places item x at a specified index i.
- Extend(iterable): Appends all of the elements from an iterable to the list to expand it. Slicing assignment a[len(a):] = iterable is equivalent to this.
- Concatenation (+): Merges lists together. To add one list to the end of another, use the + operator. Repetition (*) makes a list twice.
Changing Elements:
- L[offset] = value is an assignment that allows you to modify an item based on its index.
- Using the assignment L[start:end] = iterable, you can also modify objects with a slice.
Deleting/Removing Elements:
- To remove an item by its offset, use del list[index]. Moreover, del can remove a whole slice.
- Remove(x): Eliminates element x from the list upon its first occurrence.
- Pop(i): Returns the value after removing the element at a given point i. The last element is removed and returned by pop() if No index is supplied. Remove() utilises the value, whereas pop() uses the index. This is how the two functions differ.
- Clear(): Gets rid of every item in the list.
List Methods
You can use a collection of built-in methods on lists in Python. These are functions that are exclusive to list objects.
Here are a few list approaches that are frequently used:
- Append(x): Adds an element x to the end of the list.
- Clear(): Removes all elements from the list.
- Copy(): Returns a copy of the list.
- Count(x): Returns the number of times element x appears in the list.
- Extend(iterable): Adds the elements of an iterable to the end of the current list.
- Index(x): Returns the index of the first occurrence of element x in the list.
- Insert(i, x): Inserts an element x at a given index i.
- Pop(i): Removes the element at the given position i and returns it. If i is not specified, removes and returns the last element.
- Remove(x): Removes the first occurrence of element x from the list.
- Reverse(): Reverses the order of elements in the list in place.
- Sort(): Sorts the list in ascending order in place. The sort() method does not return a new list; it modifies the original.
The built-in functions max(), min(), sum(), and len() which returns the number of items are frequently used with lists.
Example:
my list
# sort() - sorts in place
my list sort()
print(f" After sort(): {my list}")
# count(value) - returns number of occurrences
count of 1 = my list count(1)
print(f" Count of 1: {count of 1}")
# index(value) - returns index of first occurrence
try:
index of 5 = my list index(5)
print(f" Index of 5: {index of 5}")
index of 1 = my list index(1)
print(f" Index of first 1: {index of 1}")
except Value Error:
print("Value not found in list")
# reverse() - reverses in place
my list reverse()
print(f" After reverse(): {my list}")
List
List comprehensions offer a succinct and effective method of list creation. They automatically add each new element to a single line by combining the production of new elements with a for loop. In certain ways, the syntax is similar to mathematical set notation. An expression enclosed in brackets, followed by a for clause and zero or more more for or if clauses, is what makes up a list comprehension.
Example:
# Create a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)] # Using range which can be converted to a sequence/list
print(f" Squares using list comprehension: {squares}")
# Create a list of even numbers from 0 to 20
evens = [x for x in range(21) if x % 2 == 0]
print(f" Even numbers using list comprehension: {evens}")
# Create a list of names in uppercase
names = ["chalice", "bob", "chalice"]
upper names = [name upper() for name in names]
print(f" Uppercase names using list comprehension: {upper names}")
Through iteration through the numbers produced by range (5), each number i is added to the new list.
Using a combination of operators and built-in methods, lists a fundamental and potent data type in Python offer versatile ways to store, retrieve, and work with collections of data.