Category Python List

How to Sort a Python List

How to Sort a Python List

When a list’s values are out of order, sorting puts them in the order Python compares them. Python’s list.sort() changes the list itself, while sorted() returns a new sorted list and leaves the source unchanged. I’ll show how to sort…

Convert List to JSON in Python

Convert List to JSON in Python

Saving Python list values for another program means putting them in a format it can read. JSON is a text format for values, and Python’s json module encodes a list as an array. This article shows how to write the…

Iterate Through a List in Python

Iterate Through a List in Python

Matching each name with its score means using the values at the same positions in both lists. Python’s zip() lets a loop process values from corresponding positions together. I’ll show how to choose a loop for the information each pass…

Python List Length: How to Count Items with len()

Python List Length: How to Count Items with len()

len() on a list of ten million integers takes roughly 2.5 microseconds, while a Python loop over the same list takes roughly 300 milliseconds. The difference comes from a stored count rather than a faster algorithm, which decides the length…

List Comprehension Python: Write Concise Code

List Comprehension Python: Write Concise Code

A Python list comprehension builds a new list from an iterable in one expression. Put the output expression first, then the for clause, and add an if clause when items need filtering. Start with the smallest list comprehension Use a…