In this session, we are going to discuss how to create a list in Python. The following link will help you to understand the basics and environment setup of Python.
Assign List in the Variable name
Now, we are going to discuss how to assign a list of values to a variable.
CODE
- >>> myList = []
- >>> myList
- [ ]
- >>> myList = ["PHP", "Python", "Java", "Perl"]
- >>> myList
- ['PHP', 'Python', 'Java', 'Perl']
- >>>
In the above screen, we have created the variable named “myList”. Initially, we have not assigned any value to the List. We declared the myList = [] and hit enter.
Then, you can see that an empty array has been created for myList variable on Shell.
Get specific value
If you want to get a specific value from the list, you can use the following Syntax on Python Shell.
Syntax
Variable_name[array_index]
Let’s discuss this with a live example.
CODE
- >>> myList[1]
- 'Python'
- >>> myList[2]
- 'Java'
- >>>
In the above screen, you can see that we have got a specific value from the list.
Add a new value to the List
If you want to add a new record into the List, you should use the
append keyword. Find the below screenshot for reference.
When you assign a new record, check it in the variable name on Shell.
CODE
- >>> myList
- ['PHP', 'Python', 'Java', 'Perl']
- >>> myList.append("New Language")
- >>> myList
- ['PHP', 'Python', 'Java', 'Perl', 'New Language']
- >>>
Create a new variable
Here, we are going to create a new variable and extend the value from one variable to another.
Let’s create one more variable in Python Shell. The following steps are needed to be implemented in the next step.
- Create a new variable
- Assign new records to the List
- Select the variable name in Python Shell
CODE
- >>> age = ["100","101","102"]
- >>> age
- ['100', '101', '102']
- >>>
Extend records
If you want to extend the record from one variable to another, you can use the “extend” keyword.
In the following example, we will extend the “age” records into “myList” variable.
CODE
- >>> myList.extend(age)
- >>> myList
- ['PHP', 'Python', 'Java', 'Perl', '100', '101', '102']
- >>>
As well as, you can use the existing variable name “age” records. It will not remove from the variable.
Remove a value from the List
If you want to remove the record from the List, you can use the “remove” keyword.
CODE
- >>> myList.remove("Java")
- >>> myList
- ['PHP', 'Python', 'Perl', '100', '101', '102']
- >>>
In the above screen, you can see that we have removed “Java” from the List.
Record Count in List
You can check the total counts in List by using the keyword len(variable_name).
CODE
Thank you!