Python Lists
Python Collections
There are four collection data types in python programming:- List is ordered collection. List can contain duplicate members. We can change the members of list whenever we want.
- Tuple is unordered collection. Tuple can contain duplicate members. Members of tuple cannot be changed.
- Set is unordered and unindexed collection. No duplicate members are allowed.
- Dictionary is unordered, indexed and changeable collection. Duplicate members are not allowed.
List of Contents
- How to create a list?
- Access list items
- Add new items to list
- Remove old list items
- clear() method to truncate the list
- Change the value of list item at the specified index
- Looping throught the list
- How to check if an item exists in the list
- Find the list length
- How to copy a list
- list() constructor
- Examples of list
How to create a list?
Lists are created by using[]
square brackets. The elements in the list are separated by using a comma (,). We can append any value at the end of list by using the append()
method on the list. To access elements in the list use the usual indexing starting from 0.
Example:
theList=["computer", "science","ai"]
print(theList)
''' Output of above code:-
['computer', 'science', 'ai']
'''
Access list items
You can access the list items by using index numbers.print(theList[0]) # prints computer
print(theList[1]) # prints science
print(theList[2]) # prints ai
Output:
computer science ai
If we try to access an index that does not exist it generates an exception/error.
theList=[10,20,30]
print(theList[5]) # since there are only 3 elements it will generate an error
'''Output:-
Traceback (most recent call last):
File "", line 2, in
print(mylist[10])
IndexError: list index out of range
'''
Add new items to list
Now we will append new data elements at end of list usingappend()
method.
Example:
theList.append("awesome") # appends "awesome" at the end of list
print(theList)
'''Output:-
['computer', 'science', 'ai','awesome']
'''
If you want to add an element at the specified index then you can use the insert()
method.
theList.insert(1,"python") # appends "awesome" at the end of list
print(theList)
'''Output:-
['computer', 'python', 'science', 'ai','awesome']
'''
Remove old list items
There are three ways to remove an element from the list which arepop()
, remove()
and del
.
Removing an element from list using pop() method
Thepop()
method removes an element at specified index. If index is not specified by default it removes the last element of the list. Also pop()
returns the element being removed.
Example:
theList=["computer", "science","ai"]
# removes and returns the last element
# as we are neither assinging or printing the returned value it will not be displayed
theList.pop()
print(theList)
'''Output:-
['computer', 'science']
'''
Removing an element from list using remove() method
Theremove()
method removes the first occurrence of specified element.
Example:
theList=["computer", "science","ai"]
# removes the element "science"
theList.remove("science")
print(theList)
'''Output:-
['computer','ai']
'''
Removing an element using del
del
keyword removes the element at the specified index.
Example:
theList=["computer", "science","ai"]
# removes the element at index 0
del theList[0]
print(theList)
'''Output:-
['science','ai']
'''
We can also use the del
keyword to delete the list completly.
Example:
theList=["computer", "science","ai"]
# deletes the list entirely
del theList
print(theList) #if you try to print the list it will generate an error
'''Output:-
Traceback (most recent call last):
File "main.py", line 4, in
print(theList)
NameError: name 'theList' is not defined
'''
clear() method to truncate the list
We can use theclear()
method to delete all the elements of the list. This makes the list empty. This does not delete the list.
theList=["computer", "science","ai"]
theList.clear()
print(theList) # print only square brackets as there are no elements left
'''Output:-
['science','ai']
'''
Change the value of list item at the specified index
We can change the value of the list item using the usual indexing.Example:
theList=["computer", "science","ai"]
theList[1] = "programming"
print(theList)
'''Output:-
['computer','programming','ai']
'''
Looping through the list
You can use loop throught the list using any loop available in python. The simplest way is to use thefor
loop.
Example:
theList=["computer", "science","ai"]
for x in theList:
print(x)
'''Output:-
computer
science
ai'''
How to check if an item exists in the list
Thein
keyword can be used to check if an item is present in the list.
Example:
theList=["computer", "science","ai"]
for x in theList:
if "computer" in theList:
print("The Word 'Computer' is present in the list")
'''Output:-
The Word 'Computer' is present in the list
'''
Find the list length
To calculate how many elements are present in the list, we can use thelen()
method.
Example:
theList=["computer", "science","ai"]
print(len(theList))
'''Output:-
3
'''
How to copy a list
We cannot use something likelist2 = list1
to copy the list. This will only save the reference to list1
in list2
variable. So any changes made to list1
will also reflect in list2
. So we use the built-in copy()
method to copy one list to another.
Example:
theList=["computer", "science","ai"]
theList2 = theList.copy()
print(theList2)
'''Output:-
["computer", "science","ai"]
'''
We can also use another built-in method list()
to copy the list.
theList=["computer", "science","ai"]
theList2 = list(theList)
print(theList2)
'''Output:-
["computer", "science","ai"]
'''
list() constructor
We can also make a new list using thelist()
constrtuctor.
Example:
# note the double parenthesis
theList = list(("python", "programming","list"))
print(theList)
'''Output:-
["python", "programming","list"]
'''
Examples of Lists
List of strings
This is the example of string list.names_of_languages=["java","python","rust"]
print(student_names[0])
print(student_names[1])
print(student_names[2])
Output of above code:
java
python
rust
List of mixed data types
According to the definition of the list, it can contain elements of different data types so we can create a mixed data type list as given belowmixedList=["Amar",120,240.01]
print(mixedList[0])
print(mixedList[1])
print(mixedList[2])
Output of above code:
Amar
120
240.01
List containing another list
Lists in python can also contain other lists possibly of different data types.mixedList=[1,2,3,(10,20,30),120,"python"]
print(mixedList[0])
print(mixedList[3])
print(mixedList[3][1])
Output of above code:
1
(10,20,30)
20