Programmers are always looking for ways to make their code more efficient. One way to do this is to use a faster loop. Python is a high-level programming language that is widely used by developers and software engineers. It is known for its readability and ease of use. However, one downside of Python is that its loops can be slow. This can be a problem when you need to process large amounts of data. There are several ways to make Python loops faster. One way is to use a faster looping construct, such as C. Another way is to use an optimized library, such as NumPy. Finally, you can vectorize your code, which means converting it into a format that can be run on a GPU or other parallel computing platform. By using these techniques, you can significantly speed up your Python code.
According to Vladislav Zorov, If not talking about NumPy or something, try to use list comprehension expressions where possible. Those are handled by the C code of the Python interpreter, instead of looping in Python. Basically same idea like the NumPy solution, you just don’t want code running in Python.
Example: (Python 3.0)
lst = [n for n in range(1000000)]
def loops():
newlst = []
for n in lst:
newlst.append(n * 2)
return newlst
def lstcomp():
return [n * 2 for n in lst]
from timeit import timeit
print(timeit(loops, number=100))
#18.953254899999592 seconds
print(timeit(lstcomp, number=100))
#11.669047399991541 seconds
Or Do this in Python 2.0
Python list traversing tip:
Instead of this: for i in range(len(l)): x = l[i]
Use this for i, x in enumerate(l): …
TO keep track of indices and values inside a loop.
Twice faster, and the code looks better.
Another option is to write loops in C instead of Python. This can be done by using a Python extension module such as pyximport. By doing this, programmers can take advantage of the speed of C while still using the convenient syntax of Python.
Finally, developers can also improve the performance of their code by making use of caching. By caching values that are computed inside a loop, programmers can avoid having to recalculate them each time through the loop. By taking these steps, programmers can make their Python code more efficient and faster.
Very Important: Don’t worry about code efficiency until you find yourself needing to worry about code efficiency.
The place where you think about efficiency is within the logic of your implementations.
Get 20% off Google Google Workspace (Google Meet) Standard Plan with the following codes: 96DRHDRA9J7GTN6 Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)
Weekly Thread: Meta Discussions and Free Talk Friday 🎙️ Welcome to Free Talk Friday on /r/Python! This is the place to discuss the r/Python community (meta discussions), Python news, projects, or anything else Python-related! How it Works: Open Mic: Share your thoughts, questions, or anything you'd like related to Python or the community. Community Pulse: Discuss what you feel is working well or what could be improved in the /r/python community. News & Updates: Keep up-to-date with the latest in Python and share any news you find interesting. Guidelines: All topics should be related to Python or the /r/python community. Be respectful and follow Reddit's Code of Conduct. Example Topics: New Python Release: What do you think about the new features in Python 3.11? Community Events: Any Python meetups or webinars coming up? Learning Resources: Found a great Python tutorial? Share it here! Job Market: How has Python impacted your career? Hot Takes: Got a controversial Python opinion? Let's hear it! Community Ideas: Something you'd like to see us do? tell us. Let's keep the conversation going. Happy discussing! 🌟 submitted by /u/AutoModerator [link] [comments]
Hi y'all, This might be off topic a bit from the normal stuff that gets posted here, but a while back I was messing around on a Minecraft server that I was hosting on Aternos (a free online Minecraft server host). Now since the server wasn't running on my computer (and since Aternos has a timeout policy to save server resources) it became annoying for my buddies to hop on the server if I was busy. They'd have to ask me to manually start the server from the webpage. So I had a free Saturday a couple of months ago and decided to remedy this problem. My source code is hosted on a GIGO Dev environment if y'all wanna check it out: https://www.gigo.dev/challenge/1732810200471044096 But to summarize it quickly... I used Playwright and the Discord API in Python to simulate a browser navigating to an Aternos server and starting it. For this tutorial you will need to make an Aternos acct, but their platform is free and very useful if you want to spin up a Minecraft server quickly without using your own resources. You simply need to configure a trigger command or @ the bot and set up a webhook for the the discord server you want to use. There's a full tutorial on how I set it up in the link along with the project structure, but truth be told the basic implementation is pretty simple and can be tweaked to work really however you want. Just wanted to share this to see if anyone had done something similar before, or if I'm just insane and made this mundane problem into a way bigger endeavor than it should be submitted by /u/chadicus-gigo [link] [comments]
Listen at podcast.pythontest.com/219 When starting a SaaS project using Django, there are tons of decisions. I've asked Cory Zue, creator of SaaS Pegasus, to help me sift through some common SaaS/Django decisions. submitted by /u/variedthoughts [link] [comments]
Hey folks, I have just posted an article for those who want to go a little bit beyond the basic usage of OTEL and understand how it works under the hood. The post quickly touches on: - 🔭 History and the idea of OpenTelemetry - 🧵 Distributed traces & spans. How span collection happens on the service side - 💼 Baggage & trace ctx propagation - 📈 Metrics collection. Views & aggregations. Metrics readers - 📑 OTEL Logging integration - 🤝 Semantic conventions and why that is important Blog Post: https://www.romaglushko.com/blog/opentelemetry-sdk/ Let me know what do you think and hope this is helpful for someone 🙌 submitted by /u/roma-glushko [link] [comments]
Version 1.2.0 of UXsim is released, which allows simulating taxis, shared mobility and self-driving taxis! Main Changes in 1.2.0 Add taxi (aka. shared mobility) functions A standard vehicle in UXsim just travel from A to B and disappear. This is like a private owned vehicle. From this update, a Vehicle with mode="taxi" behave like a taxi. Specifically, they travel through a network by passing through specific nodes that are dynamically updated, simulating passenger pickup and drop-off. New sub-module uxsim.TaxiHandler handles these matters. Built-in vehicle-to-passneger matching methods are also available. This addresses Issue #41 From now on, we follow the Semantic Versioning rigorously. UXsim UXsim is a free, open-source macroscopic and mesoscopic network traffic flow simulator written in Python. It simulates the movements of car travelers and traffic congestion in road networks. It is suitable for simulating large-scale (e.g., city-scale) traffic phenomena. UXsim is especially useful for scientific and educational purposes because of its simple, lightweight, and customizable features, but users are free to use UXsim for any purpose. submitted by /u/Balance- [link] [comments]
Hey everyone, I’ve recently launched a new website aimed at helping fellow programmers ace their Python interviews. It’s not just limited to Python though; it also covers essential topics like big-O notation, object-oriented programming, design patterns, and more! I’d love to hear your thoughts and feedback on the content, layout, and anything else you think could be improved. Check it out here https://hlop3z.github.io/interviews-python/ and let me know what you think. Your input is invaluable in making this resource the best it can be. Thanks in advance for your time and insights! 🚀🐍 Note: It’s mainly to be used in a computer or tablet. You can see it in your mobile, but some sections won’t look as intended. submitted by /u/ixatrap [link] [comments]
Hi. Beginning programmers should be using the same tools that we use in business. For Python that's mainly Jupyter notebooks. Google provides those free at Google Colab. I made this video to show you how to use Colab and hope that can help you. https://www.youtube.com/watch?v=JwIaYnrM7Oc submitted by /u/cyprusgreekstudent [link] [comments]
Weekly Thread: Professional Use, Jobs, and Education 🏢 Welcome to this week's discussion on Python in the professional world! This is your spot to talk about job hunting, career growth, and educational resources in Python. Please note, this thread is not for recruitment. How it Works: Career Talk: Discuss using Python in your job, or the job market for Python roles. Education Q&A: Ask or answer questions about Python courses, certifications, and educational resources. Workplace Chat: Share your experiences, challenges, or success stories about using Python professionally. Guidelines: This thread is not for recruitment. For job postings, please see r/PythonJobs or the recruitment thread in the sidebar. Keep discussions relevant to Python in the professional and educational context. Example Topics: Career Paths: What kinds of roles are out there for Python developers? Certifications: Are Python certifications worth it? Course Recommendations: Any good advanced Python courses to recommend? Workplace Tools: What Python libraries are indispensable in your professional work? Interview Tips: What types of Python questions are commonly asked in interviews? Let's help each other grow in our careers and education. Happy discussing! 🌟 submitted by /u/AutoModerator [link] [comments]
I want to hear your description of the project you are most proud of. I was just trying to find something on the Internet, but I didn't find much of interest. The only difficult project was CustomTkinter, which, as far as I know, was done entirely in Tkinter. Since it is possible to create something this complex, I'm sure you have something cool too. Note: I am expecting to hear projects more complex than a calculator 🙂 submitted by /u/_-Dan_- [link] [comments]
Just getting started with pre-commit and I think it's awesome. Looking to find out what other code automation tools people are using. Let me know what works for you and why. Thanks! submitted by /u/LatterConcentrate6 [link] [comments]
https://github.com/RadoTheProgrammer/pwdgen What my project does My project generate simple, strong, memorable and easy-to-type passwords. The system is simple: it generate 2 pronounceable words separated by a special char, with a number at start or end. I tried creating a password generator that combines simplicity, security, memorability, and ease of type. This should be secure enough because it can generate 4e15 possibilities of passwords and uses the secrets module. Target audience For anyone who need to have passwords easily. Comparison Most passwords manager generate completely passwords with completely random characters that aren't very easy to memorize or tape. Examples include Dashlane, Norton, Avast. Or other like Bitwarden generate passwords that are not really fast-to-type. The mine generate sth like 7Xy-Bonuwucete 0Qubyby+Pomafy , or 7Zuxogu:Lebuwo . Usage You can install it with pip install pwd-generator and use the cli version: pwdgen To use it in a python code import pwdgen print(pwdgen.generate()) Changes from last post I already made another post for this, but this was not well received because my code use the random module. I updated it to use the secrets module. submitted by /u/RRTheGuy [link] [comments]
I recently took a job with a professor, that includes helping with the grading of biweekly assignments. So I basically have now 30 Notebooks that I have to grade. Top of my head I can think of these approaches: Convert to PDF and write into the PDF Duplicate the Notebook and write the comments in extra blocks Create a .txt file with all my note Does anybody have experience with this and can share their workflow? submitted by /u/flying_Wahale [link] [comments]
What My Project Does? Command-line tool to simplify the management of DNS records for domains hosted on Netlify, whether you want to migrate to Netlify or migrate away from Netlify. 1. Import Zone File from Godaddy, NameCheap or others to Netlify - helpful in migrating nameservers. Export DNS records from Netlify as zonefile to be import it to Godaddy, Namecheap or other servers. Zonefile is a list of all the DNS records for a given domain Here is the url - https://github.com/sumansaurabh/netlify-dns-manager Target Audience (e.g., Is it meant for production, just a toy project, etc.) Anyone who is intended to use Netlify DNS. Comparison (A brief comparison explaining how it differs from existing alternatives.) There is no such tool that can help in managing DNS in Netlify - hence I have created it. submitted by /u/snorkell_ [link] [comments]
PyPi Source What My Project Does find_where is a Python package that provides a function to find values in dictionaries where a specified key matches a given value, similar to filtering in SQL. Target Audience This is my first attempt at creating a Python package so I would describe this as a toy project at this stage but am definitely looking for feedback from the wider community. Comparison I mainly wrote this package because I kept on writing the same iterable based code when trying to find a value, given a key: data = { "people": [ {"first_name": "John", "last_name": "Smith", "age": 25}, {"first_name": "Alice", "last_name": "Jones", "age": 32}, ] } first_name = None for result in data["people"]: if result["age"] == 32: first_name = result["first_name"] break print(first_name) When using find_where, you can simply run: from find_where import find_where data = { "people": [ {"first_name": "John", "last_name": "Smith", "age": 25}, {"first_name": "Alice", "last_name": "Jones", "age": 32}, ] } first_name = find_where(data["people"], "first_name", age=32) print(first_name) Appreciate any feedback, constructive or otherwise! submitted by /u/dan_ohn [link] [comments]
Hello everyone., on today new scraper I created the python version for the zillow scraper. https://github.com/johnbalvin/pyzill What My Project Does The library will get zillow listings and details. I didn't created a defined structured like on the Go version just because it's not as easy to maintain this kind of projects on python like on Go. It is made on pure python with HTTP requests, so no selenium, puppeteer, playwright etc. or none of those automation libraries that I hate. Target Audience This project target could be real state agents probably, so lets say you want to track the real price history of properties around an area, you can use it track it Comparison There are libraries similar outhere but they look outdated, most of the time, scraping projects need to ne on constant maintance due to changed on the page or api pip install pyzill Let me know what ou think, thanks about me: I'm full stack developer specialized on web scraping and backend, with 6-7 years of experience submitted by /u/JohnBalvin [link] [comments]
Weekly Thread: Beginner Questions 🐍 Welcome to our Beginner Questions thread! Whether you're new to Python or just looking to clarify some basics, this is the thread for you. How it Works: Ask Anything: Feel free to ask any Python-related question. There are no bad questions here! Community Support: Get answers and advice from the community. Resource Sharing: Discover tutorials, articles, and beginner-friendly resources. Guidelines: This thread is specifically for beginner questions. For more advanced queries, check out our Advanced Questions Thread. Recommended Resources: If you don't receive a response, consider exploring r/LearnPython or join the Python Discord Server for quicker assistance. Example Questions: What is the difference between a list and a tuple? How do I read a CSV file in Python? What are Python decorators and how do I use them? How do I install a Python package using pip? What is a virtual environment and why should I use one? Let's help each other learn Python! 🌟 submitted by /u/AutoModerator [link] [comments]
I was wondering if anyone has come across anything like https://github.com/a-h/templ or https://hono.dev/guides/jsx, but for python. For context, I am familiar with jinja2, mako, etc. but find them to be unintuitive due to the loose coupling of logic (ex: database calls) and templating (ex: generating a list from the database results). Therefore, I am looking for a "inline" templating solution. submitted by /u/TheRealMrMatt [link] [comments]
I'm trying to decide whether to use typeguard or stick to assert isinstance in the places where I care. Has anyone done benchmarking testing of the overhead of using type guards "at"typeguard decorator ? submitted by /u/gerardwx [link] [comments]
Hi all, I used polars (a Rust-powered “Blazingly Fast DataFrame Library”) to analyze seven years of my own music royalties data. Vega-Altair (Python wrapper for Vega-Lite) powers the (often interactive) visualizations. Link to the article: https://osc.garden/blog/data-analysis-music-streaming/ It was a lot of fun learning polars and setting up the graphs with Vega-Altair. Would love to hear any comments and suggestions. Link to r/dataisbeautiful post: https://www.reddit.com/r/dataisbeautiful/comments/1ca7x6z/oc_my_music_needs_more_than_200k_plays_on/ submitted by /u/fjogurpiano [link] [comments]
Take the excellent nuitka, compile python code to C, turn it into web assembly, and you got Python in the browser, without the usual runtime overhead: https://wasmer.io/posts/py2wasm-a-python-to-wasm-compiler While the doc states you can get this effect by doing: pip install py2wasm py2wasm myprogram.py -o myprogram.wasm wasmer run myprogram.wasm You still need the wasmer WASM runtime (curl https://get.wasmer.io -sSfL | sh for Unix users, iwr https://win.wasmer.io -useb | iex for Windows user with Powershell), however. But more than that, since you need nuikta, it means you need a C compiler installed. While in Ubuntu it's a just an sudo apt install build-essential, it will require a bit more work on Windows and Mac. submitted by /u/desmoulinmichel [link] [comments]
submitted by /u/euronews-english [link] [comments]
Today I Learned (TIL) You learn something new every day; what did you learn today? Submit interesting and specific facts about something that you just found out here.
Reddit Science This community is a place to share and discuss new scientific research. Read about the latest advances in astronomy, biology, medicine, physics, social science, and more. Find and submit new publications and popular science coverage of current research.