11 Python Looping Tips

This article is shared from Huawei Cloud Community's " Loop Skills Guide in Python " by Lemony Hug.

When we process data, sometimes we need to create multiple lists to store data of different types or conditions. In Python, we can use loops to create these lists quickly and efficiently. This article explains how to use loops to create multiple lists in Python and provides code examples.

Python uses loop to create multiple lists

In Python, we can create multiple lists using list comprehensions or loops combined with conditional statements. Here are some common scenarios and corresponding code examples:

1. Create a fixed number of empty lists

Suppose we need to create multiple empty lists, we can use list comprehensions and loops:

# Create multiple empty lists using list comprehensions
num_lists = 5
empty_lists = [[] for _ in range(num_lists)]

print(empty_lists)

This will create a list of 5 empty lists.

2. Create multiple lists based on conditions

Sometimes, we need to create different lists based on specific conditions. For example, we want to store odd and even numbers in two lists:

#Create odd and even lists
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = []
even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
    else:
        odd_numbers.append(num)

print("List of odd numbers:", odd_numbers)
print("List of even numbers:", even_numbers)

This will create two lists based on the parity of the numbers.

3. Create multiple lists based on string length

Sometimes, we need to classify and store strings in different lists based on their length:

#Create multiple lists based on string length
words = ["apple", "banana", "orange", "pear", "grape", "kiwi"]
short_words = []
medium_words = []
long_words = []

for word in words:
    if len(word) < 5:
        short_words.append(word)
    elif len(word) < 7:
        medium_words.append(word)
    else:
        long_words.append(word)

print("Short word list:", short_words)
print("Medium length word list:", medium_words)
print("Long word list:", long_words)

This will store the words in three different lists based on the length of the string.

4. Create multiple lists based on data type

Sometimes, we need to store data in different lists based on its type. For example, we want to store integers, floats, and strings in separate lists:

#Create multiple lists based on data type
data = [1, 2.5, "apple", 4, "banana", 6.7, "orange", 8, 9, "pear"]
integers = []
floats = []
strings = []

for item in data:
    if isinstance(item, int):
        integers.append(item)
    elif isinstance(item, float):
        floats.append(item)
    elif isinstance(item, str):
        strings.append(item)

print("List of integers:", integers)
print("List of floating point numbers:", floats)
print("List of strings:", strings)

This will store the data in three different lists based on its type.

5. Dynamically create multiple lists based on conditions

Sometimes, we need to create multiple lists based on dynamically changing conditions. For example, we want to create a list of corresponding quantities based on the quantity entered by the user:

# Dynamically create multiple lists based on user input
num_lists = int(input("Please enter the number of lists to create: "))
lists = [[] for _ in range(num_lists)]

print("created", num_lists, "empty lists:", lists)

This will dynamically create a corresponding number of empty lists based on the number entered by the user.

6. Create multiple lists containing specific ranges of numbers

Sometimes we need to create multiple lists based on a specific range of numbers. For example, we want to store numbers between 0 and 9 in ten lists based on single digits:

# Create multiple lists containing a specific range of numbers
num_lists = 10
range_lists = [[] for _ in range(num_lists)]

for num in range(10):
    range_lists[num % num_lists].append(num)

print("List stored in single digits:")
for i, lst in enumerate(range_lists):
    print(f"List{i}:", lst)

This will store numbers between 0 and 9 in ten separate lists, sorted by single digits.

7. Create multiple lists based on hash values ​​of keys

Sometimes, we want to store data grouped in multiple lists based on the hash value of a key. For example, we have a set of key-value pairs and we want to store them in different lists based on the hash of the keys:

# Create multiple lists based on the hash value of the key
data = {"apple": 3, "banana": 5, "orange": 2, "pear": 4, "grape": 6}
num_lists = 3
hash_lists = [[] for _ in range(num_lists)]

for key, value in data.items():
    hash_index = hash(key) % num_lists
    hash_lists[hash_index].append((key, value))

print("List stored according to hash value of key:")
for i, lst in enumerate(hash_lists):
    print(f"List{i}:", lst)

This will store the key-value pairs in three different lists based on the hash of the key.

8. Create multiple lists based on the attributes of elements in the list

Sometimes, we need to create multiple lists based on the attribute values ​​of the elements in the list. For example, let's say we have a set of student objects and we want to store them in two lists, Pass and Fail, based on their grades:

#Create multiple lists based on the scores of student objects
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

students = [
    Student("Alice", 85),
    Student("Bob", 60),
    Student("Charlie", 75),
    Student("David", 40),
    Student("Emma", 95)
]

passing_students = []
failing_students = []

for student in students:
    if student.score >= 60:
        passing_students.append(student)
    else:
        failing_students.append(student)

print("List of passing students:")
for student in passing_students:
    print(f"{student.name}: {student.score}")

print("\nList of failing students:")
for student in failing_students:
    print(f"{student.name}: {student.score}")

This will store the students in two lists, Pass and Fail, based on their grades.

9. Create multiple lists based on index ranges

Sometimes, we need to split the list into multiple sublists based on the index range. For example, we have a list containing a set of numbers and we want to split it into several smaller sublists:

#Create multiple lists based on index ranges
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_lists = 3
split_lists = []

for i in range(num_lists):
    start_index = i * len(numbers) // num_lists
    end_index = (i + 1) * len(numbers) // num_lists
    split_lists.append(numbers[start_index:end_index])

print("Split list:")
for i, lst in enumerate(split_lists):
    print(f"List{i + 1}:", lst)

This will split the original list into three sublists based on the index range.

10. Create multiple lists by grouping based on the values ​​of list elements

Sometimes, we need to group list elements based on their values ​​and store them in different lists. For example, let's say we have a set of integers and we want to store them in two lists based on their parity:

#Create multiple lists by grouping based on the values ​​of list elements
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = []
even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
    else:
        odd_numbers.append(num)

print("List of odd numbers:", odd_numbers)
print("List of even numbers:", even_numbers)

This will store the list elements in odd and even lists respectively based on their parity.

11. Create multiple lists based on whether elements meet conditions

Sometimes, we need to store elements in different lists based on whether they meet certain conditions. For example, let's say we have a set of numbers and we want to store numbers greater than or equal to 5 and numbers less than 5 in two lists:

#Create multiple lists based on whether the elements meet the conditions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
greater_than_5 = []
less_than_5 = []

for num in numbers:
    if num >= 5:
        greater_than_5.append(num)
    else:
        less_than_5.append(num)

print("List of numbers greater than or equal to 5:", greater_than_5)
print("List of numbers less than 5:", less_than_5)

This will store the number in two different lists based on whether it is greater than or equal to 5.

Summarize

Overall, this article has introduced various ways to create multiple lists using loops in Python, and has demonstrated and explained them with specific code examples. Starting from different perspectives such as fixed quantities, conditions, data types, attributes, index ranges, hash values, etc., we explored how to flexibly use loops combined with list comprehensions or conditional statements to create multiple lists. These methods not only improve the flexibility and maintainability of the code, but also speed up the development process and improve the performance of the program.

Through the study of this article, readers can master the skills of processing data in Python and organizing it into multiple lists, so as to operate and manage data more effectively. At the same time, flexible use of Python features such as loops and list comprehensions can make the code more concise, clear and elegant. In actual projects, choosing the appropriate method to create multiple lists according to specific needs will become an important skill in programming and help improve the quality and efficiency of the code.

Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~

I decided to give up on open source industrial software. Major events - OGG 1.0 was released, Huawei contributed all source code. Ubuntu 24.04 LTS was officially released. Google Python Foundation team was laid off. Google Reader was killed by the "code shit mountain". Fedora Linux 40 was officially released. A well-known game company released New regulations: Employees’ wedding gifts must not exceed 100,000 yuan. China Unicom releases the world’s first Llama3 8B Chinese version of the open source model. Pinduoduo is sentenced to compensate 5 million yuan for unfair competition. Domestic cloud input method - only Huawei has no cloud data upload security issues
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4526289/blog/11059478