List
List
•Using square bracket ([]): In this method, we can # empty list using list()
create a list simply by enclosing the items inside the my_list4 = list()
square brackets. print(my_list4)
# Output []
• my_list = [1, 2, 3]
• print(len(my_list))
• # output 3
Accessing items of a List
• Using indexing, we can access any item from a list using its index
number
• Using slicing, we can access a range of items from a list
Indexing
• We can access the items in the list using this index number.
List Slicing
• Slicing a list implies, accessing a range of elements in a list. For example, if we
want to get the elements in the position from 3 to 7, we can use the slicing
method. We can even modify the values in a range by using this slicing technique.
• The below is the syntax for list slicing.
• The start_index denotes the index position from where the slicing should begin
and the end_index parameter denotes the index positions till which the slicing
should be done.
• The step allows you to take each nth-element within a start_index:end_index
range.
• my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50]
• # Extracting a portion of the list from 2nd till 5th element
• print(my_list[2:5])
• # Output ['Jessa', 12.5, 'Emma']
my_list = [5, 8, 'Tom', 7.50, 'Emma']
# Without end_value
# Stating from 3nd item to last item
print(my_list[3:])
# Output [7.5, 'Emma']
Run
Iterating a List
• The objects in the list can be iterated over one by one, by using a for a
loop.
# iterate a list
for item in my_list:
print(item)
Run
Iterate along with an index number
• The index value starts from 0 to
(length of the list-1). Hence using the
my_list = [5, 8, 'Tom', 7.50, 'Emma']
function range() is ideal for this
scenario. # iterate a list
for i in range(0, len(my_list)):
# print each item using index number
• The range function returns a print(my_list[i])
sequence of numbers. By default, it
returns starting from 0 to the
specified number (increments by 1).
The starting and ending values can
be passed according to our needs.
Adding elements to the list
• We can add a new element/list of elements to the list using the list
methods such as append(), insert(), and extend().
Append item at the end of the list
• The append() method will accept only one parameter and add it at
the end of the list.
• Let’s see the example to add the element ‘Emma’ at the end of the
list.
my_list = list([5, 8, 'Tom', 7.50])
# Using append()
my_list.append('Emma')
print(my_list)
# Output [5, 8, 'Tom', 7.5, 'Emma']
# Using insert()
# insert 25 at position 2
my_list.insert(2, 25)
print(my_list)
# Output [5, 8, 25, 'Tom', 7.5]
• The extend method will accept the list of elements and add them at
the end of the list. We can even add another list by using this method.
•
Let’s add three items at the end of the list.
• # Using extend()
• my_list.extend([25, 75, 100])
• print(my_list)
• # Output [5, 8, 'Tom', 7.5, 25, 75, 100]
Modify the items of a List
• The list is a mutable sequence of iterable objects. It
means we can modify the items of a list. Use the index
number and assignment operator (=) to assign a new
value to an item. my_list = list([2, 4, 6, 8, 10, 12])
print(my_list)
# Output [4, 16, 36, 64]
Removing elements from a List
• The elements from the list can be removed using the following list
methods.
method Description
To remove the first occurrence of the item
remove(item)
from the list.
Removes and returns the item at the given
pop(index)
index from the list.
To remove all items from the list. The output
clear()
will be an empty list.
del list_name Delete the entire list.
Remove specific item
• Use the remove() method to remove the first occurrence of the item from the list.
# remove item 6
my_list.remove(6)
# remove item 8
my_list.remove(8)
print(my_list)
# Output [2, 4, 10, 12]
Remove all occurrence of a specific item
print(my_list)
# Output [4, 8, 12]
Remove item present at given index
• Use the pop() method to remove the item at the given index. The
pop() method removes and returns the item present at the given
index.
• It will remove the last time from the list if the index number is not
passed.
my_list = list([2, 4, 6, 8, 10, 12])
• Example
# remove item present at index 2
my_list.pop(2)
print(my_list)
# Output [2, 4, 8, 10, 12]
• # clear list
• my_list.clear()
• print(my_list)
• # Output []
# Using + operator
my_list3 = my_list1 + my_list2
print(my_list3)
# Output [1, 2, 3, 4, 5, 6]
• There are two ways by which a copy of a list can be created. Let us see
each one with an example.
Using assignment operator (=)
• This is a straightforward way of creating a copy. In this method, the
new list will be a deep copy. The changes that we make in the original
list will be reflected in the new list.
my_list1 = [1, 2, 3]
• This is called deep copying.
# Using = operator
The changes made to the original list are reflected in the copied new_list = my_list1
list as well. # printing the new list
print(new_list)
Note: When you set list= list1, you are making them refer to the
same list object, so when you modify one of them, all
# Output [1, 2, 3]
references associated with that object reflect the current state
of the object. So don’t use the assignment operator to copy the # making changes in the original list
dictionary instead use the copy() method. my_list1.append(4)
• The sort function sorts the elements in the list in ascending order.
mylist = [3,2,1]
mylist.sort()
print(mylist)
Reverse a List using reverse()
mylist = [3, 4, 5, 6, 1]
mylist.reverse()
print(mylist)
Python Built-in functions with List
• Using max() & min()
• The max function returns the maximum value in the list while the min function
returns the minimum value in the list.
mylist = [3, 4, 5, 6, 1]
print(max(mylist)) #returns the maximum number in the list.
print(min(mylist)) #returns the minimum number in the list.
• Using sum()
• The sum function returns the sum of all the elements in the list.
mylist = [3, 4, 5, 6, 1]
print(sum(mylist))
all()
• In the case of all() function, the return value will be true only when all
the values inside the list are true. Let us see the different item values
and the return values. #with all true values
Item Values in List Return Value samplelist1 = [1,1,True]
All Values are True True
print("all() All True values::",all(samplelist1))
nestedlist = [[2,4,6,8,10],[1,3,5,7,9]]
outputList = {expression(variable)
for variable in inputList [if variable condition1][if variable condition2]
expression: Optional. expression to compute the members of the output List which satisfies the optional
conditions
variable: Required. a variable that represents the members of the input List.
inputList: Required. Represents the input set.
condition1, condition2 etc; : Optional. Filter conditions for the members of the output List.
inputList = [4,7,11,13,18,20]
#creating a list with square values of only the even numbers
squareList = [var**2 for var in inputList if var%2==0]
print(squareList)
Summary of List operations
Operation Description
x in l1 Check if the list l1 contains item x.
Returns the index number of a particular item (30) in a list. But
l1.index(30, 2, 5) search Returns the item with maximum value from a list. The
x not in l2 Check if list l1 does not contain item x. answer is 60 only from index number 2 to 5.
Concatenate the lists l1 and l2. Creates a new list containing the
l1 + l2
items from l1 and l2.
Returns the item with a minimum value from a list. The answer is
min(l1)
l1 * 5 Repeat the list l1 5 times. 10.
l1[i] Get the item at index i. Example l1[2] is 30. max(l1) Returns the item with maximum value from a list. The answer is 60.
List slicing. Get the items from index i up to index j (excluding j) l1.append(100) Add item at the end of the list
l1[i:j]
as a List. An example l1[0:2] is [10, 20]
l1.append([2, 5, 7]) Append the nested list at the end
List slicing with step. Returns a List with the items from
l1[i:j:k] index i up to index j taking every k-th item. An l1[2] = 40 Modify the item present at index 2
example l1[0:4:2] is [10, 30].
Returns the number of times a particular item (60) appears in a pop(2) Removes and returns the item at index 2 from the list.
l2.count(60)
list. The answer is 2.
l1.clear() Make list empty
Returns the index number of a particular item (30) in a list. The
l1.index(30)
answer is 2 l3= l1.copy() Copy l1 into l2