Converting a string to a list of numbers in python
In Python, you can create a list from a string in several ways, depending on the format of the source string. The most common problem is a string of numbers separated by a space.
Method 1: List Comprehension Generator
This is the most common and "Pythonic" way. It is readable and fast.
# Source string
input_string = "1 2 3 4 5"
# Step 1: Splitting the string into substrings by space
string_list = input_string.split()
# Result: ['1', '2', '3', '4', '5']
# Step 2: Convert each substring to an integer
int_list = [int(num) for num in string_list]
print(int_list) # Output: [1, 2, 3, 4, 5]
# Of course, these two steps are almost always combined into one line for brevity:
int_list_oneline = [int(num) for num in input_string.split()]
print(int_list_oneline) # Output: [1, 2, 3, 4, 5]
A useful tip: The .split() method is very flexible. If the numbers in the string are not separated by a space, but, for example, by a comma, simply pass this separator as an argument: input_string.split(','). If you call .split() without arguments, it will split the string by any whitespace characters (spaces, tabs, line breaks) and delete empty lines, which is very convenient for "dirty" data.
Method 2: Using the map()
function
The map() function applies the specified function (in our case int) to each element of the sequence (in our case to the list returned by .split()). This may be slightly faster for very large amounts of data, but is often considered less readable than a list generator.
# Source string
input_string = "1 2 3 4 5"
# String splitting and transformation using map
# map() returns a special iterator object, not a list
map_object = map(int, input_string.split())
# To get the list, you need to explicitly transform this object
int_list = list(map_object)
print(int_list) # Output: [1, 2, 3, 4, 5]
Brief explanation of the functions:
input_string.split(): Turns a string into a list of substrings. "1 2 3" will become ['1', '2', '3'].
map(function, iterable): Applies function to each iterable element. map(int, ['1', '2', '3']) sequentially executes int('1'), int('2'), int('3').
list(iterable): Converts an iterable object (for example, the result of a map) into a full-fledged list.
Basic list methods
Lists in Python are mutable data structures with many useful methods.
numbers = [1, 4, 5, 6, 7, 4, 3, 2]
# .index(value): Returns the index of the first occurrence of the element.
# If the item is not in the list, a ValueError error occurs!
index_of_4 = numbers.index(4)
print(f"Index of the first four: {index_of_4}") # Conclusion: Index of the top four: 1
# .count(value): returns the number of occurrences of an element.
count_of_4 = numbers.count(4)
print(f"Number of fours: {count_of_4}") # Conclusion: Number of fours: 2
# .sort(): sorts the list "in-place", that is, it modifies the list itself.
# Returns nothing (or rather, returns None).
numbers.sort()
print(f"Sorted list: {numbers}") # Output: Sorted list: [1, 2, 3, 4, 4, 5, 6, 7]
# To sort in descending order, use the reverse=True
numbers argument.sort(reverse=True)
print(f"Sorted in descending order: {numbers}") # Output: Sorted in descending order: [7, 6, 5, 4, 4, 3, 2, 1]
# .reverse(): flips the list "in place".
numbers.reverse()
print(f"Inverted list: {numbers}") # Output: An inverted list: [1, 2, 3, 4, 4, 5, 6, 7]
# .copy(): Creates a shallow copy of the list.
# This is important when you want to change a copy without affecting the original.
numbers_copy = numbers.copy()
print(f"Copy of the list: {numbers_copy}") # Output: A copy of the list: [1, 2, 3, 4, 4, 5, 6, 7]
Important: Do not confuse the .sort() method and the built-in sorted() function.
my_list.sort() modifies my_list.
new_list = sorted(my_list) creates a new sorted list new_list, and my_list remains unchanged. This is preferable if you need to preserve the original order.
Removing items from the list
numbers = [1, 10, 2, 3, 4, 5, 6, 7]
# .remove(value): Removes the first found element with the specified value.
# If there is no such element, there will be a ValueError error.
numbers.remove(10)
print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7]
# .pop([index]): Deletes the element by index and returns it.
# If no index is specified, deletes and returns the last element.
# This is very convenient for implementing data structures like a stack.
last_element = numbers.pop() # Deleting the last element
print(f"Deleted element: {last_element}") # Output: Deleted item: 7
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
element_at_index_2 = numbers.pop(2) # Deleting the element with index 2
print(f"Deleted element: {element_at_index_2}") # Output: Deleted item: 3
print(numbers) # Output: [1, 2, 4, 5, 6]
# del operator: Deletes an element by index or an entire slice.
del numbers[1] # Deleting the element with the index 1
print(numbers) # Output: [1, 4, 5, 6]
# Deleting multiple elements using the slice
del numbers[1:3] # Deleting elements from index 1 to 3 (not including 3)
print(numbers) # Output: [1, 6]
The Council: To completely clear the list, use the .clear() (numbers.clear() method or assign an empty slice (numbers[:] = []). This is more efficient than deleting items one at a time in a loop.
List Comprehensions
It is a powerful tool for creating lists based on other sequences. General structure: [expression for element in sequence if condition].
# Creating a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Creating a list of even numbers only (filtering)
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
# Creating a list from user input
# The loop will run 3 times, each time requesting input and adding it to the list
# user_injects = [input("Enter value: ") for _ in range(3)]
# print(user_injects)
# Using the ternary operator (if/else) to convert elements
# Replace odd numbers with 0, and leave even
numbers as they are = [1, 2, 3, 4, 5, 6]
transformed_list = [x if x % 2 == 0 else 0 for x in numbers]
print(transformed_list) # Output: [0, 2, 0, 4, 0, 6]
# Combination of filtering and conversion
# Take numbers greater than 5, and if they are even, leave them, if they are odd, replace them with 0.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = [x if x % 2 == 0 else 0 for x in numbers if x > 5]
print(filtered_numbers) # Output: [6, 0, 8, 0, 10]
Remember the syntax:
- If you just need to filter the elements,
if is placed at the end: [x for x in data if x > 5]
- If you need to transform each element based on a condition, the
if/else construction is placed at the beginning: [x*2 if x > 5 else x for x in data]
zip() function
The zip() function "stitches" several lists into one sequence of pairs (tuples). This is incredibly convenient for parallel data processing.
names = ["Daniel", "Svetlana", "Valya"]
scores = [4, 6, 8]
for name, score in zip(names, scores):
print(f"{name} has the result {score}")
# Conclusion:
# Daniel has a score of 4
# Svetlana has a score of 6
# Val has a score of 8
Important: The zip() function stops as soon as the shortest of the transmitted lists ends.
names = ["Anna", "Boris", "Victor"]
ages = [25, 30]
for name, age in zip(names, ages):
print(name, age) # "Victor" will not be displayed because the ages list is shorter
# Output:
# Anna 25
# Boris 30