Monday, August 2, 2021

Stack Abuse: How to Reverse a List in Python

Introduction

Python is a flexible language, and there's typically several ways to perform the same, menial task. Choosing an approach can depend on the time or space complexity, or simply on your personal preference.

Python's data structures are quite handy and intuitive, and their built-in functionalities are easy to work with. In this article, we'll be looking at how to reverse a list in Python. A Python List is a heterogenous (can contain differing types) array-like structure that stores references to objects in memory.

When manipulating a list, we can either create a new, changed list, or change the original list in-place. We'll see the differences in these as we proceed through the article.

Reverse a List Using the reverse() Method

Python has a powerful built-in library of methods when it comes to manipulating data in data structures. For the purposes of reversing a list, we can utilize the built-in reverse() method.

Note: The reverse() method reverses the list in-place. Reversing a list in-place means that the original list is changed, instead of creating a new, reversed list.

Due to this, we can't assign the resulting object to a new variable, and if you want to keep the original list in memory, you'll have to copy it before reversing:

my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]

new_list = my_list.reverse()
print(new_list) # Output: None

There's no return value - the list is reversed in-place. However, we can copy() it before reversing:

list_1 = [1, 2, 3, 4]
list_2 = list_1.copy()

list_1.reverse()

print('Reversed list: ', list_1)
print('Saved original list: ', list_2)

This results in

Reversed list:  [4, 3, 2, 1]
Saved original list:  [1, 2, 3, 4]

Reverse a List Using Slice Notation

The slice notation allows us to slice and reproduce parts of various collections or collection-based objects in Python, such as Lists, Strings, Tuples and NumPy Arrays.

When you slice a list, a portion is returned from that list, and every stepth element is included:

my_list = [1, 2, 3, 4, 5, 6]

# list[start:end:step]
segment_1 = my_list[1:5:1]
segment_2 = my_list[1:5:2]

print(segment_1)
print(segment_2)

This results in:

[2, 3, 4, 5]
[2, 4]

By omitting the start and end arguments, you can include the entire collection. And by setting the step to a negative number, you iterate through the collection in reverse. Naturally, if you pair these together:

original_list = [1, 2, 3, 4, 5, 6]

reversed_list = original_list[::-1]
print('Original list: ', original_list)
print('Reversed list: ', reversed_list)

This results in:

Original list:  [1, 2, 3, 4, 5, 6]
Reversed list:  [6, 5, 4, 3, 2, 1]

The Slice Notation doesn't affect the original list at all, so the original_list stays the same even after the operation.

Reverse a List Using slice() Method

The slice() method accepts the very same parameters - start, end and step, and performs much the same operation as the Slice Notation. Though, instead of omitting the start and end arguments, you can pass in None.

Its return type is a Slice object, which can be then be used to slice a collection according to its contents. It's not called on the collection you're slicing - you're passing in the Slice object after creation, allowing you to create a single reusable and callable object for many different collections.

It's internally transpiled into Slice Notation, so the end result is the same:

original_list = [1, 2, 3, 4, 5, 6]

slice_obj = slice(None, None, -1)

print('slice_obj type:', type(slice_obj))
print('Reversed list:', original_list[slice_obj])

This results in:

slice_obj type: <class 'slice'>
Reversed list: [6, 5, 4, 3, 2, 1]

Reverse a List Using a For Loop

Depending on whether we want to keep the original list intact or not, we can pop() elements from the original list and add them to a new one, or we can just append them in reverse order.

pop() removes the last element from a collection and returns it. We can combine the append() method with this to directly append the removed element to a new list, effectively resulting in a reversed list:

original_list = [1, 2, 3, 4] 
reversed_list = []

for i in range(len(original_list)):
    reversed_list.append(original_list.pop())

print(reversed_list) # Output: [4, 3, 2, 1]

Alternatively, we can iterate through the list backwards, until the -1th index (non-inclusive) and add each element we see along that list. The range() method accepts 3 arguments - start, end and step, which can again be used in much the same way as before:

original_list = [1, 2, 3, 4]
reversed_list = []

for i in range(len(original_list)-1, -1, -1):
    reversed_list.append(original_list[i])

print(reversed_list) # Output: [4, 3, 2, 1]

Reversing a List Using the reversed() Method

Since iterating with a negative step and then accessing each element in the original list is a bit verbose, the reversed() method was added, which makes it much easier to manually implement the reversal logic, in case you want to add your own twist on it.

The reversed() method returns an iterator, iterating over the collection in a reversed order - and we can easily add these elements into a new list:

original_list = [1, 2, 3, 4]
new_list = []

for i in reversed(original_list):
        new_list.append(i)
    
print(new_list) # Output: [4, 3, 2, 1]
print(original_list) # Output: [1, 2, 3, 4] --> Original hasn't changed

Conclusion

Depending on whether you need a new reversed list, an in-place reversed list, as well as whether you want the logic to be taken care of for you, or if you'd like to have the flexibility of adding additional operations or twists during the reversal - there are several ways to reverse a list in Python.

In this tutorial, we've gone over these scenarios, highlighting the difference between each.



from Planet Python
via read more

Mike Driscoll: PyDev of the Week: Patrick Loeber

This week we welcome Patrick Loeber (@python_engineer) as our PyDev of the Week! Paticks runs a popular Python YouTube channel that covers Python basics, machine learning, and more! You can learn more about Patrick over on his website or support his work on Patreon.

Patrick Loeber

Let’s spend some time getting to know Patrick better!

Can you tell us a little about yourself (hobbies, education, etc):

I’m a Software Engineer from Germany with a strong interest in Computer Vision and Machine Learning applications.

I have a master’s degree in Medical Engineering, which is a mix of Mechanical Engineering, Electrical Engineering, Computer Science, and a little bit of Medicine. I actually wrote my first line of code only very late into the degree, but I enjoyed it so much that I focused on programming and then specialized in Medical Image Processing and Machine Learning. Now I’m working full-time as a Software Engineer for a company in the healthcare industry.

Two years ago I started my YouTube channel (Python Engineer) and the corresponding website python-engineer.com where I create tutorials about Python and Machine Learning.

In my free time I like to do all kinds of sports, especially running, bodyweight fitness, and soccer. And of course, I would never reject an invitation to go grab one of our famous German beers ;).

Why did you start using Python?

I did not learn Python at university, but I worked part-time as a working student during this time. The company used Python to develop GUIs and also for prototype applications where Python served as a wrapper around image processing algorithms written in C++. So I taught myself Python on this job with free online resources and immediately fell in love 🙂

What other programming languages do you know and which is your favorite?

I have the most experience with Python and C++ because I use them every day at work. I also (have to) use C# and Javascript from time to time for web development stuff.

I also taught myself Swift with an online course and even published a simple TODO app to the Appstore.

The first languages I learned at university were Matlab (if this can be considered as a programming language) and Java. But I don’t use them anymore.

From all of them, Python is still my favorite. But I also have a strong interest in learning Julia, Go, or Rust next.

What projects are you working on now?

I’m currently trying to learn more about audio data. I am more experienced in working with image data, but audio processing, e.g., for speech recognition and speech-to-text conversions is extremely interesting, too.
To get started I selected a fun project where I try to build a small game that can be controlled with voice commands.

I’m also working on a new series for my YouTube channel where I teach how to build a full-blown web app with FastAPI. Ever since I tried it I am a big fan of this web framework. It’s still pretty new but already very popular, and I think its popularity will increase even more in the near future.

Which Python libraries are your favorite (core or 3rd party)?

I like all the base libraries needed for Machine Learning and Data Science: numpy, pandas, scikit-learn, PyTorch, and TensorFlow. They are all amazing and in my opinion the main reason why Python is so popular in the Machine Learning world. I can’t imagine how we could get the job done without them.

My favorite core module is probably the collections module. It implements a lot of helpful container datatypes like deque, namedtuple, defaultdict, and Counter. I find myself using them quite a lot.

What made you decide to teach Python and Machine Learning on YouTube?

One big reason was to teach myself new stuff. I’ve heard many times that teaching is the best way to learn, so I wanted to give it a shot. Now I can say this is true! For example, I have never worked with PyTorch before and wanted to learn it, so I created a full video series for it. This is now the most popular video course on my channel, and I can confidently say that I’m an experienced PyTorch user.

Another reason was to help others get into Machine Learning. I’m very passionate about it and I know not all people have the ability to receive the education I had. So I wanted to share my knowledge and teach what I know.

What are the top three things you have learned creating content on YouTube?

1. How to edit videos. Believe it or not, but I edited my first 40 or so videos with a Python script. I even made a video on my channel where I explain my process. It can speed up certain workflows, but it’s also kinda boring and the features you can use are limited. So at some point I learned how to properly use a video editing software.

2. How to deal with criticism (99% of the comments I get is positive, but you know how the internet can be 😉 )

3. How to talk to a camera. My first videos were Screencasts only, but after a year I’ve started using a camera, too. Looking back at old videos, I think I improved a lot in presenting the content.

Is there anything else you’d like to say?

Thank you for having me on your blog! The Python community is awesome and I’m always happy to meet new people! If you want to connect you can find me on Twitter @python_engineer, and of course I’m also happy if you check out my channel!

Thanks for doing the interview, Patrick!

The post PyDev of the Week: Patrick Loeber appeared first on Mouse Vs Python.



from Planet Python
via read more

Django Weblog: Django bugfix release: 3.2.6

Today we've issued the 3.2.6 bugfix release.

The release package and checksums are available from our downloads page, as well as from the Python Package Index. The PGP key ID used for this release is Carlton Gibson: E17DF5C82B4F9D00



from Planet Python
via read more

Sunday, August 1, 2021

TestDriven.io: Supporting Multiple Languages in Django

This tutorial looks at how to add multiple language support to your Django project.

from Planet Python
via read more

Weekly Python StackOverflow Report: (cclxxxvi) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2021-08-01 06:46:48 GMT


  1. Identify index of all elements in a list comparing with another list - [13/6]
  2. How to convert vertical pandas table of 2 columns to horizontal table based on common ID value in python - [6/5]
  3. Why are np.hypot and np.subtract.outer very fast? - [6/1]
  4. how make a list unique and keep the index of eliminated items? - [5/3]
  5. Create hierarchy column in pandas - [5/2]
  6. Custom input to a Python program from a Java program - [5/2]
  7. Why does Pytorch autograd need a scalar? - [5/1]
  8. Why is 10 to the power not equal to scientific notation for large numbers in Python? - [5/1]
  9. Split a multifasta file to files with the same number of accesion numbers - [4/4]
  10. How to map two dataframe with output of overlapping items in new columns? - [4/4]


from Planet Python
via read more

Tryton News: Newsletter for August 2021

Development has slowed down a bit during the summer but improvements are still being made.

Changes for the User

The clients now only use the last menu entry as the label on each tab.

A new sales report by customer category has been added.

In order to close an accounting period, inactive accounts must now be balanced.

New Modules

The Account Stock Shipment Cost Module allocates shipment costs based on invoices.

Changes for the System Administrator

The server will now use argon2 or scrypt to hash passwords by default.

Changes for the Developer

It is now possible to use a PYSON expression as the key for a PYSON.In with a dict object.

1 post - 1 participant

Read full topic



from Planet Python
via read more

Saturday, July 31, 2021

Łukasz Langa: Weekly Report 2021, July 26 - August 1

This week I tried to drop the open pull request count below 1,400. This was a grueling task and I barely succeeded.



from Planet Python
via read more

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...