Lists in
Python
Table of Contents
01 02 03
Lists Accessing a list List Operations
Create a list Slicing Summary
04 05 06
01
Lists
Basics
Lists
★ A list is a data type that allows you to store various types data
in it.
★ List is a compound data type which means can have different-
2 data types under a list
★ for example we can have integer, float and string items in a
same list.
Lists
★ Lists are used to store multiple items in a single variable
mylist = ["apple", "banana", "cherry"]
★ List items are ordered, changeable, and allow duplicate values.
★ List items are indexed, the first item has index [0], the second item
has index [1] etc.
Lists - Ordered
★ When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
★ add new items to a list, the new items will be placed at the end of
the list.
Lists - changeable
★ The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.
Lists - Allow Duplicates
★ Since lists are indexed, lists can have items with the same value:
★ Example
★ Lists allow duplicate values:
★ thislist = ["apple", "banana", "cherry", "apple", "cherry"]
★ print(thislist)
02
Create a list
Lists
create lists # list of floats
place the items inside a square bracket []
num_list = [11.22, 9.9, 78.34, 12.0]
separated by comma
# list of int, float and strings #empty list
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"] nodata_list = []
0
3 Accessing the
items of a list
Accessing the items
in a list
Syntax to access the list items: # a list of numbers
list_name[inde numbers = [11, 22, 33, 100, 200, 300]
x]
list_name[index]
Example
# prints 11 # prints 11
print(numbers[0])
print(numbers[0])
Accessing items in a
list
1. The index cannot be a float number.
■ # a list of numbers
■ numbers = [11, 22, 33, 100, 200, 300]
■ # error
■ print(numbers[1.0])
2. The index must be in range to avoid IndexError.
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Accessing items in a
list
3. Negative Index to access the list items from the end
★ Python allows you to use negative indexes.
★ The idea behind this to allow to access the list elements
starting from the end.
★ For example an index of -1 would access the last element of
the list, -2 second last, -3 third last and so on.
Accessing items in a list
3. Example Negative Index to access the list items from the
end
# a list of strings
★ my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
★ print(my_list[-1])
# prints "world"
★ print(my_list[-3])
# prints "hello"
★ print(my_list[-4])
04
Slicing
sublist in Python using
slicing
★ sublist from a list in Python using slicing operation.
★ Lets say have a list n_list having 10 elements, then can
slice this list using colon : operator
★ Slicing example
# list of numbers
★ n_list = [1, 2, 3, 4, 5, 6, 7]
# list items from 2nd to 3rd
★ print(n_list[1:3])
sublist in Python using
slicing
★ # list items from beginning to 3rd
★ print(n_list[:3])
★ # list items from 4th to end of list
★ print(n_list[3:])
★ # Whole list
★ print(n_list[:])
05
List Operations
List Operations
★ Basic list operations used in Python programming are
★ extend() ★ concatenate(),
★ insert() ★ min() & max()
★ append() ★ count()
★ remove() ★ multiply()
★ pop() ★ sort()
★ Slice ★ index()
★ Reverse() ★ clear() etc.
★ The append() method is used to add
elements at the end of the list.
★ This method can only add a single
element at a time.
★ To add multiple elements, the append()
method can be used inside a loop.
append() - Syntax
list.append(elmnt)
append() - syntax
list.append(elmnt)
elmnt
fruits = ['apple', 'banana', 'cherry'] Required. An
fruits.append("orange") element of any type
print(fruits) (string, number,
object etc.)
Example for append() in list
List Operations
Add a list to a list:
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)
extend()
■ The extend() method adds the specified list elements (or any iterable) to
the end of the current list.
■ list.extend(iterable)
■ iterable Required. Any iterable (list, set, tuple, etc.)
■ fruits = ['apple', 'banana', 'cherry']
■ cars = ['Ford', 'BMW', 'Volvo']
■ fruits.extend(cars)
■ #Add tuple at the end of the list
■ print(fruits) ■ fruits = ['apple', 'banana', 'cherry']
■ points = (1, 4, 5, 9)
■ fruits.extend(points)
■ print(fruits)
insert()
■ The insert() method inserts the specified value at the specified position.
■ list.insert(pos, elmnt)
■ pos Required. A number specifying in which position to insert the
value
■ elmnt Required. An element of any type (string, number, object etc.)
■ fruits = ['apple', 'banana', 'cherry']
■ fruits.insert(1, "orange")
■ print(fruits)
■ fruits = ['apple', 'banana', 'cherry']
■ fruits.insert(3, "grapes")
■ print(fruits)
remove()
■ The remove() method removes the first occurrence of the element with
the specified value.
★ Syntax : list.remove(elmnt)
★ elmnt Required. Any type (string, number, list etc.)
★ The element you want to remove
#to remove banana
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
■ # removes 'e' from list2
■ list2 = [ 'a', 'b', 'c', 'd' ]
■ list2.remove('e')
pop()
★ The pop() method removes the element at the specified position.
★ list.pop(pos)
★ pos = Optional. A number specifying the position of the element
you want to remove, default value is -1, which returns the last item
#Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
■ # return the removed element
■ fruits = ['apple', 'banana', 'cherry']
■ x = fruits.pop(1)
■
reverse()
★ The reverse() method reverses the sorting order of the elements.
★ Syntax : list.reverse()
#Reverse the order of the fruit list:
fruits = ['apple', 'banana', 'cherry'] ■ # error in reverse() method
fruits.reverse() ■ # error when string is used in place of l
■ string = "abgedge"
■
■ string.reverse()
# practical application of reverse()
■ list1 = [1, 2, 3, 2, 1] ■ print(string)
■ # store a copy of list
■ list2 = list1.copy()
■ # reverse the list
■ list2.reverse()
copy()
★ copy() method returns a copy of the specified list.
★ Syntax: list.copy()
Copy the fruits list:
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
reverse () and copy()
■ # practical application of reverse() and copy()
■ list1 = [1, 2, 3, 2, 1]
■ # store a copy of list
■ list2 = list1.copy()
■ # reverse the list
■ list2.reverse()
■ # compare reversed and original list
■ if list1 == list2:
■ print("Palindrome")
■ else:
■ print("Not Palindrome")
max()
★ used to compute the maximum of the values passed in its argument
and
★ lexicographically largest value if strings are passed as arguments.
★ Syntax :
★ max(a,b,c,..,key,default)
★ Parameters : a,b,c,.. : similar type of data.
★ key : key function where the iterables are passed and comparison is
performed
★ default : default value is passed if the given iterable is empty
★ Return Value : Returns the maximum of all the arguments.
★ Exceptions : Returns TypeError when conflicting types are compared.
max()
★ max()
★ # printing the maximum of 4,12,43.3,19,100
★ print("Maximum of 4,12,43.3,19 and 100 is : ",end="")
★ print (max( 4,12,43.3,19,100 ) )
# TYPE ERROR-EXAMPLES
#code to demonstrate the Exception of min() and max()
# printing the minimum of 4,12,43.3,19, "GeeksforGeeks"
# Throws Exception
print("Minimum of 4,12,43.3,19 and Python is : ",end="")
print (min( 4,12,43.3,19,"Python" ) )
min()
★ used to compute the minimum of the values passed in its argument and
★ lexicographically smallest value if strings are passed as arguments.
★ Syntax : min(a,b,c,.., key,default)
★ Parameters : a,b,c,.. : similar type of data.
★ key : key function where the iterables are passed and comparison is
performed
★ default : default value is passed if the given iterable is empty
★ Return Value : Returns the minimum of all the arguments.
★ Exceptions : Returns TypeError when conflicting types are compared.
count()
★ The function count() returns the number of occurrences of a
given element in the list.
Syntax of List count()
★ count() Parameters :
○ takes a single argument: list.count(element)
○ element - the element to be counted
★ # create a list
★ numbers = [2, 3, 5, 2, 11, 2, 7]
★ # check the count of 2
★ count = numbers.count(2)
★ print('Count of 2:', count)
★ # Output: Count of 2: 3
Example use of count()
★ # vowels list
★ vowels = ['a', 'e', 'i', 'o', 'i', 'u']
★ # count element 'i'
★ count = vowels.count('i')
★ # print count
★ print('The count of i is:', count)
★ # count element 'p'
★ count = vowels.count('p')
★ # print count
★ print('The count of p is:', count)
multiply()
★ Python also allows multiplying the list n times.
★ The resultant list is the original list iterate n times.
m=[1,2,'Python']
print(m*2)
#output
[1, 2, 'Python', 1, 2, 'Python']
concatenate()
★ Concatenate operation is used to merge two lists and return a
single list.
★ The + sign is used to perform the concatenation.
★ Note that the individual lists are not modified, and a new
combined list is returned.
myList=[1, 2, 'Welcome ']
yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)
sort()
★ sort() method sorts the elements of a given list in a specific
ascending or descending order. sort() Syntax
list.sort(key=..., reverse=...)
★ Alternatively, use Python's built-in sorted() function for the
same purpose.
★ sorted(list, key=..., reverse=...)
★ Note: The simplest difference between sort() and sorted() is:
sort() changes the list directly and doesn't return any value,
while sorted() doesn't change the list and returns the sorted list.
sort()
★ sort() Parameters
★ By default, sort() doesn't require any extra parameters.
However, it has two optional parameters:
★ reverse - If True, the sorted list is reversed (or sorted in
Descending order)
★ key - function that serves as a key for the sort comparison
prime_numbers = [11, 3, 7, 5, 2]
# sort the list
prime_numbers.sort()
print(prime_numbers)
# Output: [2, 3, 5, 7, 11]
sort() example
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
index()
★ index() method returns the index of the specified
element in the list. Syntax of List index()
★ list index() parameters list.index(element, start, end)
★ The list index() method can take a maximum of three
arguments:
★ element - the element to be searched
★ start (optional) - start searching from this index
★ end (optional) - search the element up to this index
index()
animals = ['cat', 'dog', 'rabbit', 'horse']
Ex1: Find the index of the element # get the index of 'dog'
# vowels list index = animals.index('dog')
vowels = ['a', 'e', 'i', 'o', 'i', 'u'] print(index)
# index of 'e' in vowels # Output: 1-sample
index = vowels.index('e')
print('The index of e:', index) Ex 2: Index of the Element not Present in the List
# element 'i' is searched # vowels list
# index of the first 'i' is returned vowels = ['a', 'e', 'i', 'o', 'u']
index = vowels.index('i') # index of 'p' is vowels
print('The index of i:', index) index = vowels.index('p')
print('The index of p:', index)
index() example
Example 3: Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 1
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
clear()
★ The clear() method removes all items from the list.
Syntax of List clear()
list.clear()
★ clear() Parameters
★ The clear() method doesn't take any parameters.
Ex 1: Working of clear() method prime_numbers = [2, 3, 5, 7, 9, 11]
# remove all elements
# Defining a list
prime_numbers.clear()
list = [{1, 2}, ('a'), ['1.1', '2.2']] # Updated prime_numbers List
# clearing the list print('List after clear():', prime_numbers)
list.clear() # Output: List after clear(): []
print('List:', list)
Thank You
Next - PPT - Tuples()