List is a sequence type . It is basically an ordered collection of items enclosed within square brackets.
Eg: a=[1,2,3,4]
Note: All sequence type can be iterated over.
Indexing in a List :
It is used to refer to a particular item present in list , considering the counting starts from 0.
Example:
a=[1,2,3,4,5]
To print 5th item :
print(a[4])
#Output:5
Mutable vs Immutable Object
A mutable object is one which whose value can be changed even when defined while an immutable object is one whose value or which cannot be changed once defined.
i.e if we want to change the immutable object we have to destroy the existing one while same is not true for mutable .
Some immutable objects are :int ,float ,str ,bool ,tuple ,frozenset ,bytes.
Some mutable objects are: list ,dict ,set , bytearray
Common List Operations:
Note: Also applicable to sequence
- len():
It returns the number of items present in a list.
Example:
even=[1, 2, 3, 4]
print(len(even))
#Output: 4
- count():
It returns the number of times a specified element appears in a list.
Example:
fruits =[‘apple’, ‘banana’, ‘cherry’ ]
print(fruits.count(‘cherry’))
#Output:1
- append():
It adds a single element to the end of a list. It modifies the original list in place and does not return any value (returns None).
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)
#Output: ['apple', 'banana', 'cherry', 'orange']
- index():
It is used to find the position of an element in list ., considering counting starts from 0.
Example:
alpha=[‘x,’y’,’z’,’m’]
print(alpha.index(‘z’))
# Output: 2
- enumerate(): [:: Useful for all iterable ::]
It is a built-in function that adds a counter to an iterable and returns it as an enumerate object. This can be particularly useful when you need both the item and its index while looping over an iterable. So here list is also iterable . Hence enumerate can be used to return both object and its index .
Example:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
#Output: 0 red
1 green
2 blue
Note: can also specify a starting index for the counter by using the start parameter:
for index, color in enumerate(colors, start=1):
print(index, color)
#Output: 1 red
2 green
3 blue
- remove():
It is used to remove first occurrence of a specified item from a list. If element not found raise ValueError.
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
# Output: ['apple', 'cherry']
- extend():
It allows you to add all the elements of an iterable (like a list, tuple, or set) to the end of a list. This method does not return any value but updates the existing list with the elements of the iterable.
Example:
even=[2,4,6,8]
odd=[1,3,5,7,9]
print(even.extend(odd))
#Output:[2,4,6,8,1,3,5,7,9]
- sort() and sorted():
Sorting can be achieved using the sort() method or the sorted() function. The sort() method modifies the list in place, while sorted() creates a new list containing a sorted version of the elements in the given iterable.
Example:
even=[2,4,6,8]
print(even.sort())
#Output: [2,4,6,8] Ascending Order
For Backward or Descending Order give reverse parameter True value
print(even.sort(reverse=True))
#Output: [8,6,5,2]
Since sorted creates a new list , we assign its value to another variable.
Example:
numbers=[2.3,4.5,8.7,3.1,9.2,1.6]
sorted_numbers=sorted(numbers)
print(sorted_numbers)
#Output: [1.6,2.3,3.1,4.5,8.7,9.2]
Note :Both sort() and sorted() accept a key parameter that allows you to specify a function to be called on each list element prior to making comparisons
Example:
words = ['banana', 'pie', 'Washington', 'book']
words.sort(key=len)
print(words)
# Output: ['pie', 'book', 'banana', 'Washington']
In the above example the list will be sorted on the basis of length
- list():
It is used to create a list from any iterable . If nothing is provided it creates an empty list.
Example:
digits=list(“432985617”)
print(digits)
# Output
[“4”,”3”,”2”,”9”,”8”,”5”,”6”,”1”,”7”]
- del():
It is used to delete an item from a list. Syntax is :
del listname[index]
Example:
data=[1,2,3,4,5,6]
del data[0:2]
It will delete all values from 0 index upto 2 index but not including 2.
print(data)
#Output:
[3,4,5,6]
- reversed():
It returns an iterator that accesses the given sequence in the reverse order. It does not modify the original sequence.
Example:
original_list = [1, 2, 3, 4, 5]
reversed_iterator = reversed(original_list)
reversed_list = list(reversed_iterator)
print(original_list)
# Output: [1, 2, 3, 4, 5]
print(reversed_list)
# Output: [5, 4, 3, 2, 1]
Note:To access iterator object use loop.
alph = ["a", "b", "c", "d"]
ralph = reversed(alph)
for x in ralph
:
print(x)
#Output:
d
c
b
a
Note: reverse() and reversed() are not the same , it modifies the original list to reverse its elements.
Example:
original_list = [1, 2, 3, 4, 5]
original_list.reverse()
print(original_list)
# Output: [5, 4, 3, 2, 1]
- join():
It is used to create a string from any iterable . Here we can use list so it creates a string from a list where each item is joined via a separator.
Example:
words = ["apple", "banana", "cherry"]
separator = ", "
result = separator.join(words)
print(result)
# Output: apple, banana, cherry
- split():
It return a list from a sequence or string i.e it is used to split the string into a list. We can even specify the separator if not given by default it treats whitespace as separator.
Example:
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(“, “)
print(x)
#Output:
[‘hello’, ‘my name is Peter’,’ I am 26 years old’]