0% found this document useful (0 votes)
25 views

List Data Type in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

List Data Type in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

List Data Type in Python

Lists – lists in python are objects with ordered sequences of elements, written as comma
separated values between square brackets. The elements in list can be of same data type or
different data type. Below are examples of valid lists:

list0 = [] # Empty list


list1 = [1,2,3,4,5]
list2 = ['a', 'b', 'c', 'd', 'e']
list3 = ["Hello", "Welcome"]
list4 = [1, 2, 'a', "Good"]

Can we have elements repeated in a list? YES!! This is also a valid list:

list5 = ['a', 'b', 'c', 'b', 'a']

Nested List: We can also have a list nested as an element in another list, for example:

list6 = [1, 2, ‘a’, ‘b’, [3,4,5], “Hello”]

Here, element at index 4 is itself a list, and therefore referred to as nested list!

Accessing List Elements – list elements can be accessed in similar manner as we did with
strings. An example:

For listl4 = [1,2, 'a', "Good"], the elements are indexed as:

Positive
0 1 2 3
Index
Character 1 2 a Good
Negative Index -4 -3 -2 -1

Iterating over List: Let us consider iterating over list6 = [1, 2, ‘a’, ‘b’, [3,4,5], “Hello”]:

for i in list6:
print(i)
Or,

for i in range(len(list6)):
print(list6[i])

Similarly, we can use while loop to print list elements as:

i=0
while i < len(list1):
print(list1[i])
i +=1
Creating a list using built-in functions:

1) List Constructor – list()

We can use list() to construct an empty list or list with elements as:

list0 = list() # Creates an empty list


list1 = list([1,2,3,4,5]) # creates list [1,2,3,4,5]

list() can also be used to construct list from other data types such as strings, tuples,
set, dictionary. Example:

s1 = “aeiou” # from string


list1 = list(s1) # creates list [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

tuple1 = ('a','e','i','o','u') # from tuple


list1 = list(tuple1) # creates list [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

vowset = {'a','e','i','o','u'} # from set


list1 = list(vowset) # creates list [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

vowdict = {'a':1,'e':2,'i':3,'o':4,'u':5} # from dictionary


list1 = list(vowdict) # creates list [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

2) Range Function – We can create list by using range() function that returns an iterable
object, holding a series of values that can be iterated over. For example:

num0 = list(range(5)) will create list [0,1,2,3,4]


num1 = list(range(1,5)) will create list [1,2,3,4]
num2 = list(range(1,10,2)) will create list [1,3,5,7,9]

3) Append Function with new list – We can create list of different types by starting with
an empty list and keep appending elements to it using append function. For example:
to create a list having squares of first 10 natural numbers:

listSquare = []
for i in range(10):
listSquare.append(i*i)
print(listSquare)

will create the list: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Another way of writing the same code:

listSquare = [i*i for i in range(10)]


print(listSquare)
If we want list with square of even numbers only from first 10 natural numbers, then
we can add condition too as:

listSquare = [i*i for i in range(10) if i % 2 == 0]

Exercise -1: Create a list of first 10 natural number exponents of 2 if the number is
odd, i.e. the output should be [2, 8, 32, 128, 512].

4) Repetition operator–The operator ‘*’ acts as repetition operator with string (a


sequence type data) – this operator works the same way with other sequence type
data. With lists, repetition operator makes multiple copies of a list and joins them all
together. Example:

l5 = [0]*5 will create list [0,0,0,0,0]


l6 = [1, 2] * 3 will create list [1, 2, 1, 2, 1, 2, 1, 2]

Extracting sub-part of list or Slicing Operation– a substring of a string is called a slice.


We extract slice of a string using [::] operator, also known as slicing operator. The syntax of
this operation is:

s[start:end:step] – here, start specifies beginning index of substring and (end-1) is the
index of last character to be extracted. All the arguments – start, end and step are optional!

For example: for list, mylist = [1,2,3,4,5,6,7,8]

print(mylist[1:6:2]) will result in slice : [2,4,6]

print(mylist[::2]) will result in slice : ??

print(mylist[2::3]) will result in slice : ??

print(mylist[::]) will return : ??

print(mylist[-7:-2:2]) will result in slice : ??

Lists are mutable and dynamic: – Lists are mutable therefore, we can change an element(s)
in a list as:

mylist[0] = 0

Lists are dynamic, and so elements can be added to list or dropped from list:

mylist.append(9) or, mylist.remove(7)


The fact that lists are dynamic, becomes evident if we verify lists using id() function – the id
of mylist before changing an element, or appending a new element, or before dropping an
element remains same even after doing these operations.

Concatenating Lists: We can concatenate the two lists using ‘+’ operator:

Let, list0 = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

And, list1 = [1, 2, 3, 4, 5, 6, 7, 8]

Then, list2 = list0 + list1 # will result in a new list as:

[‘a’, ‘e’, ‘i’, ‘o’, ‘u’, 1, 2, 3, 4, 5, 6, 7, 8]

Finding element in list – we can use any of the approaches that we used for strings!

Exercise -2: Consider a list of strings, eg: [“Hello”, “Welcome”, “Python”]. Create a string
from this list by extracting first character of each string in the input list. For the given
example, output should be string: ‘HWP’.

Copying and Cloning list -

If we assign one list to another, then this will create a copy of the list – both having same id!
This means any change in one list will be reflected in another list!

The concept of copying holds true for strings too, but strings are immutable so change in any
one string will yield in creating new string.!!

If we want to modify a list and also keep a copy of the list, then we should use slicing
operation to create a clone of the list – we may keep the entire list in the new copy or only a
sub-part of it!

Example:

list1 = [1, 2, 3, 4, 5, 6, 7, 8]

list2 = list1 # will result in creating copy of list1 by the name list2, both
having same id

If, we change any element in list1, the same will be reflected in list2!

If we want to retain a sub-copy of list1, then we can clone it as:

list3 = list1[2:6] # list3 is a clone of list1 with a different id from list1


List Methods –

Method Name Description Example


append(element) Adds an element to the end of list. If list is Eg: numList = [0,1,2,3,4]
empty, then newly added element becomes
first element. This method takes exactly one numList.append(5) will result in
argument. numList = [0,1,2,3,4,5]
count(element) Counts the number of times an element Eg: numList = [1,2,1,3,2,4]
appears in the list. Returns zero if the
element is not present in the list. numList.count(1) will result in 2
index(element) Returns the lowest index of the element in Eg: numList = [1,2,1,3,2,4]
the list. Raises Value Error if the element is
not present in the list. numList.index(2) will result in 1
insert(index, Inserts an element at the specified index – Eg: numList = [1,2,1,3,2,4]
element) insert(index, element).
numList.insert(3,5) will result in
numList = [1, 2, 1, 5, 3, 2, 4]

pop(index) Removes the element present at a specified Eg: numList = [1,2,1,3,2,4]


index from the list – if no index is specified,
then it removes the last element. numList.pop(2) will result in

numList = [1, 2, 3, 2, 4]
remove(element) Removes the first instance of the element Eg: numList = [1,2,1,3,2,4]
present in the list if multiple copies of the
element exist! Raises Value Error if the numList.remove(3) will result in
element is not present in the list.
numList = [1, 2, 1, 2, 4]
reverse() Reverses the elements in the list. Eg: numList = [1,2,1,3,2,4]
numList.reverse() will result in

numList = [4, 2, 3, 1, 2, 1]
sort() Sorts the elements in the list in ascending Eg: numList = [1,2,1,3,2,4]
order.
numList.sort() will result in

numList = [1, 1, 2, 2, 3, 4]

extend(list) Extends the list with the elements present in Eg: numList = [1,2,1,3,2,4]
another list. This method doesn’t change the
id or reference of the list. & numList2 = [5, 6, 7]

numList.extend(numList2) will
result in

numList = [1, 2, 1, 3, 2, 4, 5, 6, 7]
clear() This method deletes all of the list contents, Eg: numList = [1,2,1,3,2,4]
and makes that list an empty list!
numList.clear() will result in

numList = []
del Statement with lists: pop() method removes an element from an index, remove() method
removes the input element, and clear() method deletes all the elements of the list. But, there
are situations where we need to remove only a sub-part of the list, i.e. few elements only – for
such situations, we can use del statement as:

numList = [1,2,1,3,2,4,5,6,7]

del numList[3:6]

will result in output: numList = [1, 2, 1, 5, 6, 7]

List Operations -

Method Name Description Example


len(list) Returns length (number of elements) of Eg: numList = [0,1,2,3,4]
the input list.
len(numList) will return 5 as output.

in / not in Membership check of input element in Eg: numList = [0,1,2,3,4]


the list
2 in numList will return True
5 in numList will return False
5 not in numList will return True

max(list) Returns element having the maximum Eg: numList = [0,1,2,3,4]


value in the list – the list should have
either numbers or strings (homogenous max(numList) will return 4 as output.
data)
min(list) Returns element having the maximum Eg: numList = [0,1,2,3,4]
value in the list – the list should have
either numbers or strings (homogenous min(numList) will return 0 as output.
data)
sum(list) Returns the sum of number values in the Eg: numList = [0,1,2,3,4, -2]
list. If the list contains any string element,
then the sum() operation raises error! sum(numList) will return 8 as output.
This function doesn’t work for string list.
all(list) Returns True if all elements of a list are Eg: numList = [1,0,1,1,0,1]
True (1) else returns False.
all(numList) will return False

If numList = [1,1,1,1,1,1] then the


output would be True
any(list) Returns True if at least one element of a Eg: numList = [1,0,1,0,0,1]
list is True (1) else returns False.
any(numList) will return True

If numList = [0,0,0,0,0,0] then the


output would be False
sorted(list) Returns a new list for the input list, with Eg: numList = [5,2,4,1,7,8]
elements in input list sorted in ascending
order! sorted(numList) will return new list as:

sortList = sorted(numList) and,


sortList = [1, 2, 4, 5, 7, 8]
Lists as arguments to functions or return type of a function:

Just like other data types, lists can be passed as an argument to a function or returned from a
function. Examples:

a) Passing as argument – finding average of list numbers:

def avg(numList):
total = sum(numList)
n = len(numList)
avg = total/n
return avg

numbers = [1,3,5,6,7,8]
print("Average of numbers is", avg(numbers))

b) Sending as return type from function –

def createList(s):
list_val = list(s)
return list_val

vowels_str = "aeiou"
vowels_list = createList(vowels_str)
print("List of vowels is", vowels_list)

You might also like