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

4 Surprising Ways Artificial Intelligence will Empower Consumers

Ever wonder what makes Siri search the items inside the iPhone and on the web by recognizing your voice? How does Google listening work? Artificial Intelligence and data science have already infused in this consumer-oriented generation, but we have not realized it yet. It has been quite a while that natural language processing, speech recognition, and gesture recognition system took over the market with their all new features, but what are the new things in AI that are yet to come? Few amazing transformations are: Retailing sector to become AI-ready Voice Recognition will change the game Search engines to become smarter Machine learning to bring revolutionary changes Recently we got to learn about a verbal spat between Elon Musk and Mark Zuckerberg over the probable risk and opportunities brought by AI . Believe it or not, but we already accustomed to Artificial Intelligence and probably waiting to witness jaw-dropping inventions. Some of AI inventions we have known till yet are: Mach

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.

How to use arrays in Python

Arrays in Python give you a huge amount of flexibility for storing, organizing, and accessing data. This is crucial, not least because of Python’s popularity for use in data science. But what precisely is an array? And how do you use arrays in Python? Also read: How to use dictionaries in Python Read on, and we’ll shed some light on the matter. What is an array? An array is a way to store multiple values in a single variable. That means that you can use a single “reference” in order to access your data. A list is also an example of a variable that stores multiple values, but has some slight differences. When using lists in Python, you store a series of values each with a numbered index. For example, this is how you would create a list of fruits in Python: fruits = [“apple”, “orange”, “pear”, “nectarine”] If we then say: print(fruits[3]) We will see “nectarine” appear on the screen (the first entry is stored as “0”). Also read: How to use lists in Python This is not an