Skip to main content

When to use lists vs dictionaries in Python

how to create a list in Python

One of the most fundamental and simple skills to learn as a new coder, is how to create a list in Python. But when you also have the option to create dictionaries – which are potentially more powerful – the question becomes why you should need this skill!

In this post, we’ll break down how to create a list in Python and when you should choose one over a dictionary.

How to create a list in Python and what they are for

In programming, a list is a variable that contains lots of other variables. These are added to the list in a sequential order that can then be referenced at any time. In Python, a list can contain multiple data types: strings, integers, booleans, and more.

Thus, the types of lists you build in Python will often be similar to the lists you create in real life: lists of names, lists of phone numbers, lists of places… etc.

Learning how to create a list in Python is extremely easy. Simply define a variable using square brackets, then separate the elements in the list by commas:

toDoList = ["Take out trash", "Wish Dad happy birthday", "Answer emails"]

We can then print the items in this list to the screen:

for x in range(0, len(toDoList)):

   print(toDoList[x])

Or, we can print individual items from that list:

print(toDoList[3])

Or a range:

toDoList[1:2]

(Remember, the second digit is not inclusive, and the first position on any list is indexed as “0.”)

At any point, we can now add items to the list, or insert them at specific locations in the list. For instance:

toDoList.append("Defrost chicken")

This will add the item to the end of the list.

If you want to know how to create a list in Python that’s empty, that’s also extremely straightforward:

toDoList = []
toDoList.insert(2, "Send invoice")

It’s now possible to use append and insert to populate the list programmatically. If we want to remove items, we use:

toDoList.remove(3)

And that is how to create a list in Python!

If you want to know more about this, check out the following post:

How to create a dictionary in Python

A dictionary is similar to a list, but with a key difference. That’s a pun, by the way.

The difference is that instead of being a consecutive list that uses an index, a dictionary is more like a database that stores values with a “key” to use as the reference.

We create dictionaries in a similar manner to lists, but using curly brackets and including bothkey and the value itself. For example, we might store a series of phone numbers like this:

phoneBook={"Jeff" : 7701489772,"Bill" : 7378999911, "Nancy" : 7711289354}

We could then pull out a specific person’s number by using their name:

print(phoneBook["Jeff"])

For more on using dictionaries, check out our detailed post:

When to use lists vs dictionaries

So, now you know how to create a list in Python and how to create a dictionary! The question that remains is: when do you use each? What is the benefit of one over the other?

Let’s start by looking at the obvious limitation of using lists. When we use a list in Python, we create a challenge for ourselves because the list index will change each time we add new elements. Thus it is very difficult to maintain any kind of order.

For instance, if we wanted to store phone numbers as a list but keep track of whose number each one was, the only way we could do that would be either to store two values consecutively (the name followed by the number) or to create a second list where the positions of each person were kept the same as their respective numbers.

Read also: How to round in Python

While both these options could work, they would be convoluted at best and it would be easy to get them mixed up.

What’s more, is that dictionaries are also much faster for looking up data as compared with lists!

But is a dictionary always superior? Why learn how to create a list in Python at all?

The obvious answer here, is that a list maintains order. This is important if ever we want to give a list an order. And there are many situations where this is useful: such as when assigning relative importance, for example when creating a to-do list, a sequence of levels etc.

Lists are also slightly simpler to use when you’re in a hurry if you need to store just a few items. Likewise, although dictionaries are faster, they also use up more memory as compared with a list.

As you can see then, choosing the right format in Python is a matter of knowing your objectives. Now you know how to create a list in Python, and you know when you should!


Want to take your Python knowledge further? We recommend Coding with Python: Training for Aspiring Developers, which you can nab for just $49.99, which is an absolute steal as the course is valued around $700. Check out our guide to the best online Python courses for more!



source https://www.androidauthority.com/how-to-create-a-list-in-python-1140101/

Comments

Popular posts from this blog

LIVE Day Trading Morning Show for Tuesday!

LIVE Day Trading Morning Show for Tuesday! via YouTube https://www.youtube.com/watch?v=vgagRBXRJM0 Android Tips and Tricks working hard to get the latest and useful tips and techniques that help you to solve a problem or improve your productivity.

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

How to unhide or show folders in mx player list

In this blog post, I tell you about how to Show or Hide folders from MX player list. There are two methods to Show folder from MX Player list. Method 1: Unhide / show folders If you want to temporarily Show / Unhide hidden folder from MX Player list, then go to Settings and untick Recognize .nomedia ".  Method 2: Permanently unhide / show folder: Open memory by any file explorer and I recommend X-Plore, and open the folder that is Hidden and find the file " .nomedia ". If you didn't find it, you should first enable "Show files hidden files that starts with .(dot)". Delete the file and you just need to refresh MX Player list to take changes. Note: MX Player always hide those folders which file " .nomedia " exists.