02 Lists
02 Lists
Data Structure:
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation.
A data structure is a collection of data elements (such as numbers or characters—or even other data structures) that is structured in some
way, for example, by numbering the elements. The most basic data structure in Python is the "sequence".
-> Lists are collection of items (Strings, integers or even other lists)
List Creation
To create a list in Python, we use square brackets []
In [1]: emptyList = []
print(lst)
print(lst2)
print(lst3)
print(lst4)
List Length
we can use the built-in len() function to find the length of a list.
The len() function accepts a sequence or a collection as an argument and returns the number of elements present in the sequence or
collection
print(len(lst))
print(len(lst2))
4
6
append()
The append() method adds an item to the end of the list
Syntax: list.append(object)
In [3]: # Example
lst = ['one', 'two', 'three', 'four']
lst.append("iota")
print(lst)
In [4]: # Example
lst = ['one', 'two', 'three', 'four']
lst.append(2)
lst.append(4)
print(lst)
Note: The append() method modifies the original list. It doesn't return any value.
In [6]: # Example
lst = [11,22,33]
print(lst.append(44))
None
extend()
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list
Syntax: list.extend(iterable)
# append
lst.append(lst2)
print(lst)
len(lst)
lst.extend(lst2)
print(lst)
print(len(lst))
insert()
The insert() method inserts an element to the list at the specified index.
In [8]: # Example
lst = ['one', 'two', 'four']
print(lst)
remove()
The remove() method removes the first matching element (which is passed as an argument) from the list.
Syntax: list.remove(value)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[10], line 3
1 # raises ValueError if item is not present in the list
2 lst = ['one', 'two', 'three', 'four', 'two']
----> 3 lst.remove("five")
In [11]: # Example
pop()
The pop() method removes the item at the given index from the list and returns the removed item.
Syntax: list.pop(index)
If index is not passed, it will remove the last element of the list because the default index is -1
popped_item = lst.pop(2)
print(popped_item)
print(lst)
three
['one', 'two', 'four', 'two']
popped_item = lst.pop()
print(popped_item)
print(lst)
two
['one', 'two', 'three', 'four']
clear()
The clear() method removes all items from the list.
Syntax: list.clear()
del
The del keyword removes items from the specified index as well as having the ability to delete the entire list although it is not a list
method.
Syntax:
del lst[1]
print(lst)
reverse()
The reverse() method reverses the elements of the list.
Syntax: list.reverse()
lst.reverse()
print(lst)
sort()
the sort() method sorts the items of a list in ascending or descending order.
*reverse* - If True, the sorted list is reversed (or sorted in Descending order)
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements
is maintained).
sorted()
The easiest way to sort a List is with the sorted(list) function.
That takes a list and returns a new list with those elements in sorted order.
The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards.
sorted_lst = sorted(numbers,reverse=False)
Count()
The count() method returns the number of times the specified element appears in the list.
Syntax: list.count(value)
# frequency of 1 in a list
print(numbers.count(1))
# frequency of 3 in a list
print(numbers.count(3))
2
2
if 'two' in lst:
print('AI')
AI
ML
True
Out[23]:
lst = [1, 2, 3, 4, 5]
abc = lst
abc.append(6)
List Indexing
Each item in the list has an assigned index value starting from 0.
syntax: variable_name[index]
2
3
List Slicing
Accessing parts of segments is called slicing.
The key point to remember is that the :end value represents the first value that is not in the selected slice.
syntax: variable_name[start:end]
[10, 20, 30, 40, 50, 60, 70, 80, ['IOTA', 'Academy']]
[10, 20, 30, 40]
In [29]: # Example
numbers[::-1] # print the list in reverse order
[['IOTA', 'Academy'], 80, 70, 60, 50, 40, 30, 20, 10]
Out[29]:
In [30]: # Example
numbers[::2] # here stepsize is 2
In [32]: # Example
numbers[:5] # print from index 0 to index 4
In [33]: # Example
numbers[-1].append('for Python')
numbers
[10, 20, 30, 40, 50, 60, 70, 80, ['IOTA', 'Academy', 'for Python']]
Out[33]:
In [34]: numbers[-1][0]
'IOTA'
Out[34]:
In [35]: print(numbers[-1])
type(numbers[-1])
[10, 20, 30, 40, 50, 60, 70, 80, ['IOTA', 'Academy', 'for Python']]
[10, 30, 50, 70, ['IOTA', 'Academy', 'for Python']]
[20, 40, 60, 80]
In [37]: numbers[6:1:-2]
In [38]: numbers[-3:1:-2]
print(new_lst)
List Looping
In [40]: # loop through a list
one
two
three
four
0
I am one
1
I am two
2
I am three
3
I am four
Common applications are to make new lists where each element is the result of some operations applied to each member of another
sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
In [44]: #example
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(transposed)
In [46]: matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
matrix
In [47]: matrix[1][2]
7
Out[47]:
That's Great