Python Lists
Python Lists
Lists
Introduction
A list is a standard data type of Python that can store a sequence of values
belonging to any type. The Lists are contained within square brackets ( [ ] ).
Following are some examples of lists in Python:
[ ] #Empty list
[1, 2, 3] #List of integers
[1, 2, 5.6, 9.8] #List of numbers (Floating point and Integers)
['a', 'b', 'c'] #List of characters
['a', 1, 4.3, "Zero"] #List of mixed data types
["One", "Two", "Three"] #List of strings
Creating Lists
In Python programming, a list is created by placing all the items (elements) inside
square brackets [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
A list can also have another list as an element. Such a list is called a Nested List.
1
Fahad sayyed – note-7
Linked in @ fahad sayyed
Operations On Lists
Accessing Elements in a List
List indices start at 0 and go on till 1 less than the length of the list. We can use the
index operator [ ] to access a particular item in a list. Eg.
Index: 0 1 2 3 4
1 10 34 23 90
Note: Trying to access indexes out of the range (0 ,lengthOfList-1), will raise an
IndexError. Also, the index must be an integer. We can't use float or other types,
this will result in TypeError.
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. The negative indexing starts from the
last element in the list.
2
Fahad sayyed – note-7
Linked in @ fahad sayyed
Positive Indexing: 0 1 2 3 4 →
1 10 34 23 90
Negative Indexing: -5 -4 -3 -2 -1 ←
Output:
Concatenation of Lists
Joining or concatenating two list in Python is very easy. The concatenation operator (+), can
be used to join two lists. Consider the example given below:
3
Fahad sayyed – note-7
Linked in @ fahad sayyed
Output:
[1,2,3,3,4,5]
Note: The + operator when used with lists requires that both the operands are of
list types. You cannot add a number or any other value to a list.
Repeating/Replicating Lists
Like strings, you can use * operator to replicate a list specified number of times.
Consider the example given below:
Notice that the above output has the same list l1 repeated 3 times within a single
list.
List Slicing
List slicing refers to accessing a specific portion or a subset of a list while the
original list remains unaffected. You can use indexes of list elements to create list
slices as per the following syntax:
● The StartIndex represents the index from where the list slicing is supposed
to begin. Its default value is 0, i.e. the list begins from index 0 if no
StartIndex is specified.
● The StopIndex represents the last index up to which the list slicing will go on.
4
Fahad sayyed – note-7
Linked in @ fahad sayyed
Its default value is (length(list)-1) or the index of the last element in the
list.
● The list slices created, include elements falling between the indexes
StartIndex and StopIndex, including StartIndex and not including
StopIndex.
As, you can see from the figure given above, we get the output as:
5
Fahad sayyed – note-7
Linked in @ fahad sayyed
below.
6
Fahad sayyed – note-7
Linked in @ fahad sayyed
['c','e','g']
You can even specify a negative step size:
['g','e','c']
Output
7
Fahad sayyed – note-7
Linked in @ fahad sayyed
Whereas, omitting the StopIndex extends the slice to the end of the list. Meaning,
L[start:] is equivalent to L[start:len(L)].
Output
Reversing a List
You can reverse a list by omitting both StartIndex and StopIndex and specifying
steps as -1.
Output:
['e', 'd', 'c', 'b', 'a'] #Reversed List
List Methods
append(): Used for appending/adding elements at the end of a list.
Syntax: <ListName>.append(element)
Example:
>>> li=[1,2,3,4]
>>> li.append(5) #Append 5 to the end of the list
>>> li
[1,2,3,4,5]
8
Fahad sayyed – note-7
Linked in @ fahad sayyed
>>> l1=[1,2,3,4]
>>> l2=[5,6,7,8]
>>> l1.extend(l2) #Adds contents of l2 to l1 at the end
>>> l1
[1,2,3,4,5,6,7,8]
**.append() vs .extend():
The only difference between .append() and .extend() is that, the .append()
method adds an element at the back of a given list (appends an element at the end of
a list). On the other hand, the .extend() method adds the contents of another list
at the end of the given list i.e. it merges two lists (extends the given list). See the
examples given above for better clarity.
>>> li=[1,2,3,4]
>>> li.insert(2,5) #Insert 5 at the index no. 2
>>> li
[1,2,5,3,4]
9
Fahad sayyed – note-7
Linked in @ fahad sayyed
sum() : Returns the sum of all the elements of a List. (Used only for lists containing
numerical values)
Syntax: sum(<ListName>)
Example:
>>> l1=[1,2,3,4]
>>> sum1= sum(l1) #Finds the sum of all elements in l1
>>> sum1
10
count(): Returns the total number of times a given element occurs in a List.
Syntax: <ListName>.count(element)
Example:
>>> l1=[1,2,3,4,4,3,5,4,4,2]
>>> c= l1.count(4) #Number of times 4 occurs in the list
>>> c
4
>>> l1=[1,2,3,4,5]
>>> len(l1)
5
10
Fahad sayyed – note-7
Linked in @ fahad sayyed
>>> l1=[1,2,3,4]
>>> l1.index(3)
2
>>> l1=[1,2,3,4]
>>> min(l1)
1
>>> l1=[1,2,3,4]
>>> max(l1)
4
pop(): It deletes and returns the element at the specified index. If we don't mention
the index, it by default pops the last element in the list.
Syntax: <ListName>.pop([index])
Example:
>>> l1=[1,2,3,4]
11
Fahad sayyed – note-7
Linked in @ fahad sayyed
>>> l1=[1,1,12,3]
>>> del l1[2]
>>> l1
[1,1,3]
Example:
>>> l1=[1,1,12,3]
>>> l1.remove(12)
>>> l1
[1,1,3]
Looping On Lists
There are multiple ways to iterate over a list in Python.
12
li = [1, 3, 5, 7, 9]
# Using for loop
for i in li:
print(i) #Print the element in the list
Output:
1
3
5
7
9
list = [1, 3, 5, 7, 9]
length = len(list) #Getting the length of the list
for i in range(length): #Iterations from 0 to (length-1)
print(i)
Output:
1
3
5
7
9
You can even use while() loops. Try using the while() loops on your own.
13
Taking Lists as User Inputs
There are two common ways to take lists as user inputs. These are:
14
print(li) #Print the list
The above code will prompt the user to input 5 integers in 5 lines. These 5 integers
will be appended to a list and the list will be printed.
Example :
In[]: a= input().split()
In[]: print(a)
User[]: 1 2 3 4 5 #User inputs the data (space separated input)
Out[]: ['1','2','3','4','5']
Now, say you want to take comma separated inputs, then you will use "," as the
separator. This will be done as follows:
In[]: a= input().split(",")
In[]: print(a)
15
User[]: 1,2,3,4,5 #User inputs the data (space separated input)
Out[]: ['1','2','3','4','5']
Note: Observe that the elements were considered as characters and not integers in
the list created using the split() function. (What if you want a list of integers?- Think)
Example :
Here, In[1] typecasts x in the list input().split() to an integer and then makes
Linear Search
Linear search is the simplest searching algorithm that searches for an element in a
list in sequential order.
16
Linear Search Algorithm
We have been given a list and a targetValue. We aim to check whether the given
targetValue is present in the given list or not. If the element is present we are
required to print the index of the element in the list and if the element is not
present we print -1.
(First, let us implement this using a simple loop, then later we will see how to implement
linear search using functions.)
Pseudo-Code
Python Code
17
found = False #Boolean value to check if we found the targetValue
for i in li:
if (i==targetValue): #If we found the targetValue
print(li.index(i)) #Print the index
found = True #Set found as True as we found the targetValue
break #Since we found the targetValue, we break out of loop
if found is False:#If we did not find the targetValue
print(-1)
We have:
User[1]: 1 2 4 67 23 12 #User input for list
User[2]: 4 #User input= targetValue
Out[]: 2 #Index of 4
We will create a function linearSearch, which will have the following properties:
● Take list and targetValue as parameters.
● Run a loop to check the presence of targetValue in list.
● If it is present then it returns the index of the targetValue.
● If it is not present, then it returns -1.
We will call this function and then print the return value of the function.
Python Code
def linearSearch(li,targetValue):
18
for i in li:
if (i==targetValue): #If we found the targetValue
return li.index(i) #Return the index
return -1 #If not found, return -1
li= [int(x) for x in input().split()] #Taking list as user input
targetValue= int(input()) #User input for targetValue
print(linearSearch(li,targetValue)) #Print the return value
The Python data types can be broadly categorized into two - Mutable and
Immutable types. Let us now discuss these two types in detail.
Note: Objects of built-in types like (int, float, bool, str, tuple, Unicode) are immutable.
Objects of built-in types like (list, set, dict) are mutable. A list is a mutable as we can
insert/delete/reassign values in a list.
19