Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

What is List in Python Programming Language

Python can store both strings and numbers together in a group or collection. This group or collection if mutable (modifiable) is called List in Python programming language. A list is similar to array as in most of other programming languages like Java and C++. The benefit of the list is that you can do things or perform an action to the whole of collection or list at once and keep track of groups of things more easily.
Lists are very useful, and they’re used in a lot of programs. If you are a game developer, you need lists quite often.
 

Understanding of list in Python Programming Language

If I asked you to make a list of your friends, you might write something like this:
Adam
John
Mark
Bill
In Python, you’d write the same thing in this way:
friends = ['Adam','John', 'Mark', 'Bill']
Above friends are the example of Python list and the individual things inside square brackets are called items or elements. As you can see, lists in Python Programming language aren’t much different from lists you make in everyday life. square brackets in a list show that from where the list starts and ends, and it uses commas to separate the items inside.

 

How to Create a list in Python

On the left hand side “friends” in the above mentioned list is a variable. We know that we can assign different types of values to a variable. As we know that we can assign strings and numbers to a variable, in the same way, we can assign a list to a variable. You create a list like you create any other variable by assigning something to it, just like we did with friends.

 

How to create an empty list in Python

You can also create an empty list, like this:
emptyList = []
There are no items or elements inside the square brackets.

 

How to add items in the list in Python

To add items to already existing list, we use append() method.

Output:
['John']
In the above example append() method adds john into an empty list of friends.
Now we will add one more friend to our friend list. Look at the following code.

output:
[‘John’, ‘Bill’]

 

Python list Can Hold anything

Lists can hold any kind of data that python supports, it includes number, strings, objects etc. Different types of items can be stored in a single list. Look at the following example.
myList = [1,2,3,'a','b','c']
123 is the numeric data type and a b c is string data type. In the above example both item are stored in a single list.

 

LearnAndLearn.com © 2018 - All rights reserved