The python list is a conceptual data structure that includes one or more items, where some items may appear more than once and there is no indexing system with the exception of the first index which always refers to the element at 0.
Each item contains a distinct order and if the same value occurs multiple times, it will only be counted as one item in that sequence and not several different variations of it.
A Python list can be defined as either being mutable or immutable depending on whether its elements are modified during runtime
How to create a Python list
In this Python tutorial, you will learn how to create python lists and the common
paradigms for a python list
companies = ["PythonSourcecode", "google", "facebook"]
# get the first company name
print(companies[0])
'PythonSourcecode'
# get the second company name
print(companies[1])
'google'
# get the third company name
print(companies[2])
'facebook'
# try to get the fourth company name
# but this will return an error as only three names
# have been defined.
print(companies[3])
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
Trying to access elements outside the range will give an error. You can create a two-dimensional
list.
How to add elements to the Python List
- list.append(elem) – will add another element to the list at the end
# create an empty list
companies = []
# add “hackerearth” to companies
companies.append("pythonsourceocde")
# add "google" to companies
companies.append("google")
# add "facebook" to companies
companies.append("facebook")
# print the items stored in companies
print(companies)
['pythonsourceocde', 'google', 'facebook']
This python append list output
['pythonsourceocde', 'google', 'facebook']
How to Remove Python list
- list.remove(elem) – will search for the first occurrence of the element in the list and will then
remove it.
langs.remove("scala")
print(langs)
- list.pop() – will remove the last element of the list. If the index is provided, then it will remove
the element at the particular index.
How to python list sort
- list.sort() – will sort the list in-place.
and how to reverse Python list
- list.reverse() – will reverse the list in place