List Data Type in Python
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:
Can we have elements repeated in a list? YES!! This is also a valid list:
Nested List: We can also have a list nested as an element in another list, for example:
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])
i=0
while i < len(list1):
print(list1[i])
i +=1
Creating a list using built-in functions:
We can use list() to construct an empty list or list with elements as:
list() can also be used to construct list from other data types such as strings, tuples,
set, dictionary. Example:
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:
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]
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].
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!
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:
Concatenating Lists: We can concatenate the two lists using ‘+’ operator:
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’.
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!
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]
List Operations -
Just like other data types, lists can be passed as an argument to a function or returned from a
function. Examples:
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))
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)