Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is List in python?
Lists are used to store multiple items in a single variable.
a list is created by placing all the items (elements) inside square brackets [], separated by commas.
List store different types of data such as (integer, float, string etc.).
Lists are mutable, meaning their elements can be changed unlike string or tuple.
File name : index.py
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Sana", 3.14]
File name : index.py
thislist = ["Mahtab", "Bebs", "Nusrat","Sana"]
print(thislist)
A list can also have another list as an item. This is called a nested list.
File name : index.py
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to Access List Elements in python?
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError
File name : index.py
# List indexing
my_list = ['p', 'r', 'o', 'b', 'e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
# Error! Only integer can be used for indexing
print(my_list[4.0])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
File name : index.py
# Negative indexing in lists
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
Output :-
e
p
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator :(colon).
File name : index.py
# List slicing in Python
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Output :-
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Change List Elements
We can use the assignment operator = to change an item or a range of items.
File name : index.py
# Correcting mistake values in a list
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
print(odd)
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
Add List elements
We can add one item to a list using the append() method or add several items using extend() method.
File name : index.py
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.extend([9, 11, 13])
print(odd)
Output
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
concatenation
use + operator to combine two lists. This is also called concatenation. The * operator repeats a list for the given number of times.
File name : index.py
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5])
print(["re"] * 3)
Output
[1, 3, 5, 9, 7, 5]
['re', 're', 're']
insert() Method:-
we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
File name : index.py
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
Output
[1, 3, 9]
[1, 3, 5, 7, 9]
Delete/Remove List Elements
We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
File name : index.py
# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
Output
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
Traceback (most recent call last):
File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined
Remove
We can use remove() method to remove the given item or pop() method to remove an item at the given index. The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure). We can also use the clear() method to empty a list.
File name : index.py
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear()
# Output: []
print(my_list)
Output
['r', 'o', 'b', 'l', 'e', 'm']
o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]
Python List Methods
File name : index.py
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of the number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Example
File name : index.py
# Python list methods
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Output
1
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]
keyword in
an item exists in a list or not, using the keyword in.
File name : index.py
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
Output
True
False
True
Loop List
For loop
File name : index.py
thislist = ["Ankita","mahtab", "Himanshu", "Ravi", "Anup Tiwari","Satendra","Minhaj","Najim","Ezaz","Prasant","Hari"]
for x in thislist:
print(x)
Loop Through the Index Numbers
File name : index.py
thislist = ["Ankita","mahtab", "Himanshu", "Ravi", "Anup Tiwari","Satendra","Minhaj","Najim","Ezaz","Prasant","Hari"]
for i in range(len(thislist)):
print(thislist[i])
Using a While Loop
File name : index.py
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
Sort List
File name : index.py
thislist = ["Ankita","mahtab", "Himanshu", "Ravi", "Anup Tiwari","Satendra","Minhaj","Najim","Ezaz","Prasant","Hari"]
thislist.sort()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True
File name : index.py
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Iterating Through a List
Using a for loop we can iterate through each item in a list
File name : index.py
for fruit in ['apple','banana','mango']:
print("I like",fruit)
Output
I like apple
I like banana
I like mango
List Length
To determine how many items a list has, use the len() function:
File name : index.py
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output
3
type()
File name : index.py
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Output:-
The list() Constructor
use the list() constructor when creating a new list.
File name : index.py
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Output:-
['apple', 'banana', 'cherry']
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.
File name : index.py
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
File name : index.py
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Use the extend() method to add list2 at the end of list1:
File name : index.py
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
File name : index.py
File name : index.py
File name : index.py