How to Quickly Extract Elements From Lists in Python

https://miro.medium.com/max/1200/0*1wK46_l4VchGqcaY

Original Source Here

How to Quickly Extract Elements From Lists in Python

A guide on quickly extracting elements from lists in Python.

Photo by Stefan Rodriguez on Unsplash

There can be many cases when you want to get elements from a list of named variables and not have to always use indexes.

For example, let us assume that we have a list that has five elements:

my_list = [1, 2, 3, 4]

Now we want to save the value of the first element in the list in a variable called one and the remaining elements in separate variables so that it is easier for us to reference them instead of memorizing the exact indexes in the list.

To do that, we can simply declare the names of the variables and separate them via commas, as can be shown down below:

my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list

Yes, it’s that simple.

This way, we can from now on simply use the variables that we have just created thus decreasing the likelihood of potential mistakes that may arise from using wrong indexes when referencing elements in the list.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: