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

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...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...