Sign In
Sign In

How to Add Elements to an Array in Python

How to Add Elements to an Array in Python
Anees Asghar
Technical writer
Python
18.12.2024
Reading time: 6 min

In Python, inserting items into arrays is a frequent task. Arrays hold data of a single type and can be initialized with lists, the array module, or through NumPy. Although Python lacks a native array type, both the array module and the NumPy library offer flexible options for managing arrays. Each approach provides unique methods for inserting elements, based on specific needs.

Functions such as append() and extend() allow us to add items to built-in arrays. List comprehension is helpful for generating new arrays. For more complex tasks, NumPy offers tools like append(), concatenate(), and insert() to add elements, particularly when dealing with numerical or structured data. Each approach is useful for specific situations.

In this tutorial, we will demonstrate all available techniques for inserting elements into an array in Python.

Adding Values to Python's Inbuilt Arrays

Python provides different methods for inserting values into its inbuilt arrays. These functions allow us to add items at the start, end, or a specific array position. Let’s go through the following methods to understand how they work and which one fits your needs.

Method 1: array.append()

append() is a useful array method that lets us insert a single value at the last index of the target array. It modifies the original array:

from array import array 

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
print("Modified Array: ")
AuthorsIDs.append(140)
print(AuthorsIDs)

Initially, the AuthorIDs array has 12, 110, and 13 as its elements. Next, we invoke append() on the AuthorIDs array to insert 140 at the last position:

Image4

Here, we utilize i to assign signed integers to AuthorIDs. Similarly, users can specify type codes like f, u, d, etc. to assign float, Unicode, and double-type data to an array.

Method 2: array.extend()

Array module offers another useful function extend() that lets us add numerous items at the end of an array. It expands the actual array:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
AuthorsIDs.extend([19, 105, 16])
print("Modified Array: ")
print(AuthorsIDs)

This time, we extend AuthorsIDs with a sub-array of three items:

Image6

Method 3: array.insert()

insert() is an inbuilt array function that lets us add values at an index of our choice and shift the subsequent entries accordingly. It accepts two arguments a value to be added and an index at which the value will be placed:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
AuthorsIDs.insert(2, 55)
print("Modified Array: ")
print(AuthorsIDs)

Here, we add 55 at the third index of AuthorIDs:

Image5

Method 4: List Comprehension

List comprehension lets us integrate new values with existing ones to create an updated array. It doesn’t alter the actual array; instead, it generates a new array based on the given logic:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
newIDs = [14, 51]
AuthorsIDs = array('i', [x for x in AuthorsIDs] + newIDs)
print("Modified Array: ")
print(AuthorsIDs)  

The newIDs are successfully merged with the AuthorIDs through list comprehension:

Image8

Method 5: Plus Operator

The plus operator + joins the provided arrays. It enables us to add one or more values to the target array:

from array import array

AuthorsIDs = array('i', [12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
newIDs = array('i', [14, 51, 72])
totalIDs = AuthorsIDs + newIDs 
print("Modified Array: ")
print(totalIDs) 

The + operator successfully integrates the AuthorsIDs and newIDs arrays while preserving the initial ones:

Image7

Add Elements to NumPy Array

NumPy is a commonly utilized Python library in data science and numerical computing. It aids in handling arrays and executing arithmetic operations. Various functions, including append(), concatenate(), and insert(), can be employed to add values to NumPy arrays.

Method 1: numpy.append()

The append() method of the numpy module adds elements at the end of an array and retrieves a new array. It lets us insert one or more values to a numpy array. Let's import the NumPy library and invoke append() to add the desired elements to the last of AuthorIDs:

import numpy as npy

AuthorsIDs = npy.array([12, 110, 13])
print("Original Array: ")
print(AuthorsIDs)
updatedIDs = npy.append(AuthorsIDs, [140, 31])

print("Modified Array: ")
print(updatedIDs)

It successfully appends 140 and 31 at the right/last of AuthorsIDs:

Image2

Method 2: numpy.concatenate()

NumPy offers a very useful function named concatenate() that merges multiple numpy arrays. Let’s invoke the concatenate() function to integrate the AuthorIDs with newIDs array:

import numpy as npy

AuthorsIDs = npy.array([12, 110, 13])
newIDs = npy.array([101, 1, 31])
concatenatedIDs = npy.concatenate((AuthorsIDs, newIDs))
print("Modified Array: ")
print(concatenatedIDs)

We store the concatenated values in a new array named concatenatedIDs:

Image1

Method 3: numpy.insert()

The numpy.insert() function provides the flexibility to place one or more values at any given index of the target array:

import numpy as npy

AuthorsIDs = npy.array([1, 103, 41])
print("Original Array: ")
print(AuthorIDs)
newIDs = npy.insert(AuthorsIDs, 1, 102)
print("Modified Array: ")
print(newIDs)

It successfully appended 102 at the first index of AuthorsIDs:

Image3

Best Practices

When managing arrays in Python, the append() method is utilized to insert a single value to the final index of the array. To include multiple elements, you can employ extend() or the + operator. Additionally, the insert() method enables adding elements at specific positions within the array, making it versatile for various use cases.

In contrast, NumPy arrays offer more specialized functions for managing data efficiently. numpy.append() is used for appending data, while numpy.concatenate() merges multiple arrays. numpy.insert() can be used for precise insertions.

NumPy functions are generally preferred for tasks involving large datasets or numerical computations due to their better performance and scalability.

Conclusion

In this tutorial, we demonstrated distinct inbuilt and numpy functions for appending elements to Python arrays.

Users can utilize several methods to append values to Python arrays, based on the array type and specific use case. For inbuilt arrays, append(), extend(), and insert() allow easy modifications, while list comprehension and the + operator provide additional flexibility for merging arrays. 

When operating with NumPy arrays, append(), concatenate(), and insert() offer advanced functionality, especially for quantitative and data science tasks. For larger datasets or more complex operations, you should prefer NumPy due to its efficiency and performance. 

If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman. 

Python
18.12.2024
Reading time: 6 min

Similar

Python

How to Use f-strings in Python

Python f-strings, introduced in Python 3.6, revolutionized how developers format strings. These possess abilities of being precise, readable, & highly powerful which makes these a preferred method for string interpolation in Python. This manual covers all that there is so that you learn about all the different aspects about f-strings of python. It covers basic usage & goes all the way to advanced formatting techniques. Introduction Formatting a string is an integral part of programming in Python, helping developers to dynamically include data within strings. Among different processes of formatting strings, f-strings stand out because of their simplicity and performance benefits. f-strings are also known as formatted string literals. First came out  in Python 3.6, f-strings blend flexibility & efficiency, making them a go-to choice for many developers. This manual will provide a detailed elaboration of f-strings, covering their syntax, features, & practical applications. By the end, you will be an expert in using f-strings effectively. It also proves much efficient for your code & is also better readable. f-strings are also called formatted string literals.These are used for inserting expressions or variables, as well as function outputs directly. For creating an f-string, you can prefix string with either an uppercase or lowercase f. After that whatever will be placed in curly braces {} will be a part of the string. It will also be printed as if it was part of that string. Benefits of f-strings Using f-strings offers numerous benefits, including: Enhanced Readability: Due to these there is seamless embedding of Variables & Expressions into strings Improved Performance: As compared to other techniques that are used for formatting like str.format() or %-based formatting, they have faster performance. Flexibility: Supports nested formatting, calling functions. & calculations. f-strings Syntax Its syntax is very straightforward. f"string with {expression}" Basic syntax example:  name = "Alice" age = 30 greeting = f"My name is {name}, and I am {age} years old." print(greeting) Output: My name is Alice, and I am 30 years old. Core functions of f-strings Let’s dive into the essential features of f-strings. Using Expressions Inside f-strings F-strings not only embed  variables; they also allow the inclusion of any valid Python expression within the curly braces. Example: x = 10 y = 20 result = f"The sum of {x} and {y} is {x + y}." print(result) Output: The sum of 10 and 20 is 30. Formatting of numbers in f-strings Formatted string literals provide an elegant way to display numbers with specific formatting options, like rounding, padding, or converting values to percentages. Example: pi = 3.14159formatted_pi = f"Value of pi: {pi:.2f}"print(formatted_pi) Output: Value of pi: 3.14 Escaping Curly Braces For some cases, curly braces are used in the output text itself. To display literal curly braces in an f-string, use double braces {{ and }}. Example: template = f"Use {{braces}} to include special characters."print(template) Output: Use {braces} to include special characters. Multiline f-strings F-strings can span multiple lines, making them useful for constructing large text blocks while maintaining readability. Example: title = "Python f-strings" description = "powerful, fast, and easy to use" message = f""" Title: {title} Description: f-strings are {description}. """ print(message) Output: Title: Python f-stringsDescription: f-strings are powerful, fast, and easy to use. Nesting and Combining f-strings F-strings can contain other f-strings or be combined with traditional strings. This capability is helpful for dynamic and complex outputs. Example: name = "Bob"info = f"{name.upper()}: {f'Name has {len(name)} characters'}"print(info) Output: BOB: Name has 3 characters Handling Lists and Dictionaries With f-strings, you can directly access elements from lists or keys in dictionaries. Example with Lists: items = ["Python", "JavaScript", "C++"]favorite = f"My favorite programming language is {items[0]}."print(favorite) Output: My favorite programming language is Python. Example with Dictionaries: data = {"name": "Eve", "role": "Developer"}message = f"{data['name']} works as a {data['role']}."print(message) Output: Eve works as a Developer. f-Strings vs. Other string Methods Now, let's compare f-strings with other types of strings methods in python.  % Formatting vs. f-Strings The % operator, an older method, uses placeholders like %s for strings and %d for integers. While functional, it can be cumbersome and error-prone. Example: # % Formatting name = "Alice" age = 25 print("Hello, %s. You are %d years old." % (name, age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: % formatting requires tuples and placeholder matching, increasing complexity. Python f-strings embed variables directly, making the code simpler and easier to read. str.format() vs. f-Strings The str.format() method introduced named placeholders, improving readability over % formatting. However, it still requires method calls, which can feel verbose. Example: # str.format() print("Hello, {}. You are {} years old.".format(name, age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Advanced Example: Named placeholders: # str.format() with named placeholders print("Hello, {name}. You are {age} years old.".format(name=name, age=age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: str.format() improves over % formatting but can still feel clunky. f-strings streamline the process, especially for dynamic expressions. String Concatenation vs. f-Strings String concatenation combines strings using the + operator. While straightforward, it becomes inefficient for more complex formatting needs. Example: # String concatenation print("Hello, " + name + ". You are " + str(age) + " years old.") # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: Concatenation requires explicit type conversion, increasing verbosity. Python f-strings handle formatting and type conversion automatically. Advanced Example: Including expressions: # String concatenation years_later = 5 print(name + " will be " + str(age + years_later) + " in " + str(years_later) + " years.") # Equivalent f-string print(f"{name} will be {age + years_later} in {years_later} years.") Practical Applications of f-Strings in Python Whether you're crafting dynamic SQL queries, improving logging efficiency, or processing data for analytics, f-strings in Python simplify your workflow and enhance code readability. Generating Dynamic SQL Queries In applications involving databases, f-strings perform really well to construct dynamic SQL queries by embedding variables directly into the query string. Example: # Generating SQL queries using f-strings table_name = "users" condition = "age > 30" sql_query = f"SELECT * FROM {table_name} WHERE {condition};" print(sql_query) # Output: SELECT * FROM users WHERE age > 30; By embedding variables into the SQL query string, f-strings in Python reduce the risk of syntax errors and make the code intuitive. Enhancing Logging Statements Logging plays an important role in debugging and monitoring applications. Python f-strings simplify logging statements, especially at the time at which dynamic data is included. Example: # Logging with f-strings username = "Alice" action = "logged in" print(f"User {username} has {action} at 10:30 AM.") # Output: User Alice has logged in at 10:30 AM. Working with data for analytics purposes Because of the use of f-strings, formatting strings dynamically based on variable content, is possible. This enables efficient and concise manipulation of data. Example: # Processing analytics data metric = "conversion rate" value = 7.5 print(f"The {metric} has increased to {value}%.") # Output: The conversion rate has increased to 7.5%. Crafting Dynamic File Paths Automating the handling of a file often involves dynamically generating file paths. Python f-strings have made this process straightforward. Example: # Generating dynamic file paths directory = "/data/exports" filename = "report_2024.csv" path = f"{directory}/{filename}" print(path) # Output: /data/exports/report_2024.csv Dynamic Web Content Generation During web development, HTML or JSON content can be generated dynamically by the use of f-strings. Example: # Dynamic HTML generation title = "Welcome" content = "This is a demo of Python f-strings in action." html = f"<h1>{title}</h1><p>{content}</p>" print(html) # Output: <h1>Welcome</h1><p>This is a demo of Python f-strings in action.</p> Automating titles of report During reporting or analytics, titles often need to reflect about data that is being processed. f-strings in Python automate this with ease. Example: # Automating report titles report_date = "December 2024" report_title = f"Sales Report - {report_date}" print(report_title) # Output: Sales Report - December 2024 Advanced Formatting Features f-strings are capable of handling alignment, width specifications, or time & date  formatting for creation of cleaner outputs. Example: # Aligning text for name, score in [("Alice", 92), ("Bob", 87)]: print(f"{name:<10} | {score:>5}") # Formatting dates from datetime import datetime now = datetime.now() print(f"Current time: {now:%Y-%m-%d %H:%M:%S}") Debugging Made Easier with f-Strings f-strings are capable of showing error messages in more informative by embedding relevant expressions or variables. Example: value = 42 try: assert value > 50, f"Value {value} is not greater than 50." except AssertionError as e: print(e) Common Errors to Avoid During the use of f-strings, a few common pitfalls include: Forgetting to prefix the string with f: This results in a plain string without any formatting. Incompatible Python versions: Ensure Python 3.6 or newer is installed, as f-strings are not supported in earlier versions. Conclusion F-strings are a robust and versatile tool for string formatting in Python. Whether you need to include variables, perform calculations, or debug your code, f-strings simplify such types of tasks with cleaner syntax & better performance. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
19 December 2024 · 9 min to read
Python

The Walrus Operator in Python

The first question newcomers often ask about the walrus operator in Python is: why such a strange name? The answer lies in its appearance. Look at the Python walrus operator: :=. Doesn't it resemble a walrus lounging on a beach, with the symbols representing its "eyes" and "tusks"? That's how it earned the name. How the Walrus Operator Works Introduced in Python 3.8, the walrus operator allows you to assign a value to a variable while returning that value in a single expression. Here's a simple example: print(apples = 7) This would result in an error because print expects an expression, not an assignment. But with the walrus operator: print(apples := 7) The output will be 7. This one-liner assigns the value 7 to apples and returns it simultaneously, making the code compact and clear. Practical Examples Let’s look at a few examples of how to use the walrus operator in Python. Consider a program where users input phrases. The program stops if the user presses Enter. In earlier versions of Python, you'd write it like this: expression = input('Enter something or just press Enter: ') while expression != '': print('Great!') expression = input('Enter something or just press Enter: ') print('Bored? Okay, goodbye.') This works, but we can simplify it using the walrus operator, reducing the code from five lines to three: while (expression := input('Enter something or just press Enter: ')) != '': print('Great!') print('Bored? Okay, goodbye.') Here, the walrus operator allows us to assign the user input to expression directly inside the while loop, eliminating redundancy. Key Features of the Walrus Operator: The walrus operator only assigns values within other expressions, such as loops or conditions. It helps reduce code length while maintaining clarity, making your scripts more efficient and easier to read. Now let's look at another example of the walrus operator within a conditional expression, demonstrating its versatility in Python's modern syntax. Using the Walrus Operator with Conditional Constructs Let’s write a phrase, assign it to a variable, and then find a word in this phrase using a condition: phrase = 'But all sorts of things and weather must be taken in together to make up a year and a sphere...' word = phrase.find('things') if word != -1: print(phrase[word:]) The expression [word:] allows us to get the following output: things and weather must be taken in together to make up a year and a sphere... Now let's shorten the code using the walrus operator. Instead of: word = phrase.find('things') if word != -1: print(phrase[word:]) we can write: if (word := phrase.find('things')) != -1: print(phrase[word:]) In this case, we saved a little in volume but also reduced the number of lines. Note that, despite the reduced time for writing the code, the walrus operator doesn’t always simplify reading it. However, in many cases, it’s just a matter of habit, so with practice, you'll learn to read code with "walruses" easily. Using the Walrus Operator with Numeric Expressions Lastly, let’s look at an example from another area where using the walrus operator helps optimize program performance: numerical operations. We will write a simple program to perform exponentiation: def pow(number, power): print('Calling pow') result = 1 while power: result *= number power -= 1 return result Now, let’s enter the following in the interpreter: >>> [pow(number, 2) for number in range(3) if pow(number, 2) % 2 == 0] We get the following output: Calling pow Calling pow Calling pow Calling pow Calling pow [0, 4, 16] Now, let's rewrite the input in the interpreter using the walrus operator: >>> [p for number in range(3) if (p := pow(number, 2)) % 2 == 0] Output: Calling pow Calling pow Calling pow [0, 4, 16] As we can see, the code hasn’t shrunk significantly, but the number of function calls has nearly been halved, meaning the program will run faster! Conclusion In conclusion, the walrus operator (:=) introduced in Python 3.8 streamlines code by allowing assignment and value retrieval in a single expression. This operator enhances readability and efficiency, particularly in loops and conditional statements. Through practical examples, we’ve seen how it reduces line counts and minimizes redundant function calls, leading to faster execution. With practice, developers can master the walrus operator, making their code cleaner and more concise. On our app platform you can deploy Python applications, such as Celery, Django, FastAPI and Flask. 
23 October 2024 · 4 min to read
Python

Python String Functions

As the name suggests, Python 3 string functions are designed to perform various operations on strings. There are several dozen string functions in the Python programming language. In this article, we will cover the most commonly used ones and several special functions that may be less popular but are still useful. They can be helpful not only for formatting but also for data validation. List of Basic String Functions for Text Formatting First, let’s discuss string formatting functions, and to make the learning process more enjoyable, we will use texts generated by a neural network in our examples. capitalize() — Converts the first character of the string to uppercase, while all other characters will be in lowercase: >>> phrase = 'the shortage of programmers increases the significance of DevOps. After the presentation, developers start offering their services one after another, competing with each other for DevOps.' >>> phrase.capitalize() 'The shortage of programmers increases the significance of devops. after the presentation, developers start offering their services one after another, competing with each other for devops.' casefold() — Returns all elements of the string in lowercase: >>> phrase = 'Cloud providers offer scalable computing resources and services over the internet, enabling businesses to innovate quickly. They support various applications, from storage to machine learning, while ensuring reliability and security.' >>> phrase.casefold() 'cloud providers offer scalable computing resources and services over the internet, enabling businesses to innovate quickly. they support various applications, from storage to machine learning, while ensuring reliability and security.' center() — This method allows you to center-align strings: >>> text = 'Python is great for writing AI' >>> newtext = text.center(40, '*') >>> print(newtext) *****Python is great for writing AI***** A small explanation: The center() function has two arguments: the first (length of the string for centering) is mandatory, while the second (filler) is optional. In the operation above, we used both. Our string consists of 30 characters, so the remaining 10 were filled with asterisks. If the second attribute were omitted, spaces would fill the gaps instead. upper() and lower() — convert all characters to uppercase and lowercase, respectively: >>> text = 'Projects using Internet of Things technology are becoming increasingly popular in Europe.' >>> text.lower() 'projects using internet of things technology are becoming increasingly popular in europe.' >>> text.upper() 'PROJECTS USING INTERNET OF THINGS TECHNOLOGY ARE BECOMING INCREASINGLY POPULAR IN EUROPE.' replace() — is used to replace a part of the string with another element: >>> text.replace('Europe', 'USA') 'Projects using Internet of Things technology are becoming increasingly popular in the USA.' The replace() function also has an optional count attribute that specifies the maximum number of replacements if the element to be replaced occurs multiple times in the text. It is specified in the third position: >>> text = 'hooray hooray hooray' >>> text.replace('hooray', 'hip', 2) 'hip hip hooray' strip() — removes identical characters from the edges of a string: >>> text = 'ole ole ole' >>> text.strip('ole') 'ole' If there are no symmetrical values, it will remove what is found on the left or right. If the specified characters are absent, the output will remain unchanged: >>> text.strip('ol') 'e ole ole' >>> text.strip('le') 'ole ole o' >>> text.strip('ura') 'ole ole ole' title() — creates titles, capitalizing each word: >>> texttitle = 'The 5G revolution: transforming connectivity. How next-gen networks are shaping our digital future' >>> texttitle.title() 'The 5G Revolution: Transforming Connectivity. How Next-Gen Networks Are Shaping Our Digital Future' expandtabs() — changes tabs in the text, which helps with formatting: >>> clublist = 'Milan\tReal\tBayern\tArsenal' >>> print(clublist) Milan Real Bayern Arsenal >>> clublist.expandtabs(1) 'Milan Real Bayern Arsenal' >>> clublist.expandtabs(5) 'Milan Real Bayern Arsenal' String Functions for Value Checking Sometimes, it is necessary to count a certain number of elements in a sequence or check if a specific value appears in the text. The following string functions solve these and other tasks. count() — counts substrings (individual elements) that occur in a string. Let's refer again to our neural network example: >>> text = "Cloud technologies significantly accelerate work with neural networks and AI. These technologies are especially important for employees of large corporations operating in any field — from piloting spacecraft to training programmers." >>> element = "o" >>> number = text.count(element) >>> print("The letter 'o' appears in the text", number, "time(s).") The letter 'o' appears in the text 19 time(s). As a substring, you can specify a sequence of characters (we'll use text from the example above): >>> element = "ob" >>> number = text.count(element) >>> print("The combination 'ob' appears in the text", number, "time(s).") The combination 'in' appears in the text 5 time(s). Additionally, the count() function has two optional numerical attributes that specify the search boundaries for the specified element: >>> element = "o" >>> number = text.count(element, 20, 80) >>> print("The letter 'o' appears in the specified text fragment", number, "time(s).") The letter 'o' appears in the specified text fragment 6 time(s). The letter 'o' appears in the specified text fragment 6 time(s). find() — searches for the specified value in the string and returns the smallest index. Again, we will use the example above: >>> print(text.find(element)) 7 This output means that the first found letter o is located at position 7 in the string (actually at position 8, because counting in Python starts from zero). Note that the interpreter ignored the capital letter O, which is located at position zero. Now let's combine the two functions we've learned in one code: >>> text = "Cloud technologies significantly accelerate work with neural networks and AI. These technologies are especially important for employees of large corporations operating in any field — from piloting spacecraft to training programmers." >>> element = "o" >>> number = text.count(element, 20, 80) >>> print("The letter 'o' appears in the specified text fragment", number, "time(s), and the first time in the whole text at", (text.find(element)), "position.") The letter 'o' appears in the specified text fragment 3 time(s), and the first time in the whole text at 7 position. index() — works similarly to find(), but will raise an error if the specified value is absent: Traceback (most recent call last): File "C:\Python\text.py", line 4, in <module> print(text.index(element)) ValueError: substring not found Here's what the interpreter would return when using the find() function in this case: -1 This negative position indicates that the value was not found. enumerate() — a very useful function that not only iterates through the elements of a list or tuple, returning their values, but also returns the ordinal number of each element: team_scores = [78, 74, 56, 53, 49, 47, 44] for number, score in enumerate(team_scores, 1): print(str(number) + '-th team scored ' + str(score) + ' points.') To output the values with their ordinal numbers, we introduced a few variables: number for ordinal numbers, score for the values of the list, and str indicates a string. And here’s the output: 1-th team scored 78 points. 2-th team scored 74 points. 3-th team scored 56 points. 4-th team scored 53 points. 5-th team scored 49 points. 6-th team scored 47 points. 7-th team scored 44 points. Note that the second attribute of the enumerate() function is the number 1, otherwise Python would start counting from zero. len() — counts the length of an object, i.e., the number of elements that make up a particular sequence: >>> len(team_scores) 7 This way, we counted the number of elements in the list from the example above. Now let's ask the neural network to write a string again and count the number of characters in it: >>> network = 'It is said that artificial intelligence excludes the human factor. But do not forget that the human factor is still present in the media and government structures.' >>> len(network) 162 Special String Functions in Python join() — allows you to convert lists into strings: >>> cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio'] >>> cities_str = ', '.join(cities) >>> print('Cities in one line:', cities_str) Cities in one line: New York, Los Angeles, Chicago, Houston, Phoenix, Philadelphia, San Antonio print() — provides a printed representation of any object in Python: >>> cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio'] >>> print(cities) ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio'] type() — returns the type of the object: >>> type(cities) <class 'list'> We found out that the object from the previous example is a list. This is useful for beginners, as they may initially confuse lists with tuples, which have different functionalities and are handled differently by the interpreter. map() — is a fairly efficient replacement for a for loop, allowing you to iterate over the elements of an iterable object, applying a built-in function to each of them. For example, let's convert a list of string values into integers using the int function: >>> numbers_list = ['4', '7', '11', '12', '17'] >>> list(map(int, numbers_list)) [4, 7, 11, 12, 17] As we can see, we used the list() function, "wrapping" the map() function in it—this was necessary to avoid the following output: >>> numbers_list = ['4', '7', '11', '12', '17'] >>> map(int, numbers_list) <map object at 0x0000000002E272B0> This is not an error; it simply produces the ID of the object, and the program will continue to run. However, the list() method is useful in such cases to get the desired list output. Of course, we haven't covered all string functions in Python. Still, this set will already help you perform a large number of operations with strings and carry out various transformations (programmatic and mathematical). On our app platform you can deploy Python applications, such as Celery, Django, FastAPI and Flask. 
23 October 2024 · 9 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support