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

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 a web API from your Android app

Credit: Adam Sinicki / Android Authority A Web API is an online “application programming interface” that allows developers to interact with external services. These are the commands that the developer of the service has determined will be used to access certain features of their program. It is referred to as an interface because a good API should have commands that make it intuitive to interact with. An example of this might be if we want to get information about a user from their social media account. That social media platform would likely have a web API for developers to use in order to request that data. Other commonly used APIs handle things like advertising ( AdMob ), machine learning ( ML Kit ), and cloud storage. It’s easy to see how interacting with these types of services could extend the functionality of an app. In fact, the vast majority of successful apps on the Play Store will use at least one web API! In this post, we’ll explore how to use a web API from withi...

How to Hide and Show Videos in MX Player

We use android apps to hide our personal data from gallery or any viewing source. These Applications use mobile memory and use a lot of RAM and these type of Applications is major cause of battery power wastage. Now I will tell you about a tip  to hide videos from MX Player list without using Android Application. Step 1: Put all those videos which you want to hide in a folder. Step 2: Create an blank file and name it as ".nomedia " and  place this file inside the folder  where are targeted hidden videos are present. Step 3: Now check MX Player and the videos and those videos which you put on that folder would have been ignored (hidden) Refresh MX Player list if these showed again. To show hidden Videos just remove the " .nomedia " file. Note: No need to hide the folder and there is no need of any application.  MX Player hide the videos where the file " .nomedia " exists.