Skip to main content

How to use lists in Python

How to use lists in Python

Credit: Adam Sinicki / Android Authority

A string is a variable that allows you to store multiple variables with an index. This is an extremely powerful tool in programming and one that you will find yourself using again and again. In this post, we’ll see how lists work, how to create them, and how to add to a list in Python!

What are lists?

A list is a collection of variables. Let’s use the example of a string. A string is a variable that stores a string of alphanumeric characters and symbols. This is used to store such things as names and places, as well as to display text on the screen to users.

Also read: Best online Python courses

But sometimes a string is not enough. For example, imagine that you are making a quiz with multiple questions. You want to be able to bring up these questions at random, programmatically, and add to the list at any time.

One way of doing this would be to create hundreds of individual strings. We’d then need to make some kind of massive, nested “IF/THEN” statement in order to sort through the list. In pseudo code:

IF randomQuestionNumber = 1 THEN PRINT “What is the capital of England”

ELSE IF randomQuestionNumber = 2 THEN PRINT “Who is the president of the United States?”

ELSE IF randomQuestion = 3 THEN PRINT….

You get the picture!

This is not optimal.

Instead, we would add all of our strings to a long list. Think of this like a filing cabinet that contains our strings.

We do this in Python like so:

questions = ["What is the capital of England?", "Who is the president of the United States?", "What is the value of Pi to 5 digits?"]

As with so many other things, creating lists in Python is extremely straight forward! All you need to do is to place the items that make up your list inside square brackets, separated by a comma.

Now you know how to add to a list in Python any time you want to insert more questions: just write an extra item inside the square brackets!

Also read: What is Python and how do you get started?

What’s even better, is that you don’t need to define the data type as Python can work that out for us. We can even mix data types within our list:

questions = ["What is the capital of England?", 3, "Who is the president of the United States?", "What is the value of Pi to 5 digits?"]

How to add to a list in Python

If you want to know how to add to a list in Python programmatically, or how to append to a list in Python, you simply use the following:

questions.append("How many continents are there?")

This will append an additional item to the end of the list.

But what if we want to know how to add to a list in Python while placing the new value at a different position? For example, what if we want to insert a new third question?

To do that, we would use:

questions.insert(2, "Who was the first man on the moon?")

The number is the “index” (i.e. the point where we want to insert our value), and the string is the data we are entering.

You may notice something strange here: in order to add a new third question, we are using the index 2. The reason for this seeming lunacy, is that list indexes always start at 0. This is true for all programming.

So, if you want to insert something at the start of the list, you do so like this:

questions.insert(0, "Who was the first man on the moon?")

Keep in mind that when you insert a new item in your list this way, you will change the position of all subsequent entries too.

If you want to store data in a non-linear fashion, then you can do so using another tool called a dictionary. But that is a conversation for another time!

To delete items from a list, you can likewise use: delete() or clear(). Clear will empty the entire list, whereas delete will let you choose an index in order to remove a specific item.

How to retrieve items from a list

Now, what if we want to retrieve one of these items?

This is really easy too! Simply use the name of your list as you would do with any other variable, and then place the index in square brackets behind it. For example:

print(questions[2])

This will print the entry with the index “2” to the screen.

If we wanted to print the entire list, then we could do so like this:

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

   print(questions[x])

This For loop will run incrementally increase the value of x from 0 to the length of the list.

Put all the code together to get a grip on how to append to a list in Python, and do everything else we’ve just learned:

questions = ["What is the capital of England?", "Who is the president of the United States?", "What is the value of Pi to 5 digits?"]

questions.append("How many continents are there?")

print(len(questions))

questions.insert(2, "Who was the first man on the moon?")

print(questions[2])

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

   print(questions[x])

Now you know how to create and append to a list in Python! Of course, were we really building a quiz I would recommend storing your questions in a separate file and then pulling the list from there. That way, you wouldn’t need to know how to add to a list in Python as you could simply update your text file. But that is a story for another time!

Also read: How to call a function in Python

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.

$49 .99
Coding with Python: Training for Aspiring Developers Bundle
Save $641 .01
Buy it Now
Coding with Python: Training for Aspiring Developers Bundle Buy it Now
Save $641 .01 $49 .99


source https://www.androidauthority.com/how-to-add-to-a-list-in-python-1134815/

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 AWS – a simple guide for beginners

Amazon Web Services (AWS) is Amazon’s powerful, market-leading solution for cloud computing. The platform offers a suite of products for businesses: security, cloud backup, machine learning, IoT solutions, and more. In this post, we will explore how to use AWS. What you need to know Many entrepreneurs and small businesses may assume that AWS is not for them. Perhaps the pricing will be too prohibitive, or it will require too much technical know-how. While both of these issues certainly do crop up from time-to-time, the truth is that Amazon’s offerings are extremely wide-reaching and include options at many different price points and levels of complexity. That is to say, that while some products might be off-limits, others are not. Some AWS products are completely free and very simple to get to grips with! See also: AWS vs Azure vs Google Cloud – Which certification is best for professionals? AWS includes over 175 different products, some of which don’t even require an AWS accou...

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.