List:
The list is a versatile data type exclusive in Python.[1,”33”,44.44]
it can simultaneously hold different types of data.
Creation of a list
list is an ordered sequence of some data written using square brackets([]) and commas(,)
List index starts from 0
a = []
print(type(a))
Example:
a = [22,11,33,55,44,88,77]
print(a)
a = [“Abc”,22,77.88,’xyz’]
print(a)
Manipulation
add elements in list:
There are two ways to add elements in a list.
A. append() - used to add a single element in a list. (increased the list count by 1).
B. extend() - used to add multiple elements in a list.(increased the list count by the number of elements provided in it.).
list = [12,33,11,44,7,25]
list.append(5)
print(list)
list.extend([1,3,55,21])
print(list)
To Add elements on specified index
- insert(index,ele)
- The insert() method doesn't return anything; returns None. It only updates the current list.
a = [11,33,44,22]
a.insert(5,88)
print(a)
Access elements from list:
- By using index we can access elements from the list.
- nested lists are accessed using a nested index.
- list index starts from 0. If in your list having 10 elements then indexing will be 0 to 9.
- list also supports negative indexing means (-1 to -10 if 10 elements in your list). -1 indicates the last position element from the list.
print(list[5])
print(list[0])
print(list[-1])
a = [“Chaitanya”,1234,[22,33,44,5]]
print(a[0][3])
#print(a[1][3])
print(a[1][3])
Change the elements from list:
- list is mutable, it means we can change the list elements.
- using range operators we can change multiple elements at a time.
a[0]= “Sagar”
print(a)
a[1:5] = [“Sachin”,”Laxman”]
print(a)
remove elements from the list.
There are 3 methods used to remove or delete elements from the list
remove():
- It removes the first matching element.
- If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception.
remove(item)
a = [22,33,55,99,33]
print(a.remove(33))
print(a.remove(11))pop():
- This method removes the item at the given index from the list and returns the removed item.
-The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).
- If the index passed to the method is not in range, it throws IndexError: pop index out of range exception.
a = [22,11,55,66,77,44,33]
print(a.pop(3))
print(a)
print(a.pop(12))
clear()
- The clear() method removes all items from the list.
print(a.clear())
print(a)
5. Search elements
- The index() method returns the index of the specified element in the list.
- index(ele,start,end) #optional start and end
- If the element is not found, a ValueError exception is raised.
a = [22,44,11,22,66,77,44]
print(a.index(44))
print(a.index(77,3,9))
6. Get Element count
- count() method returns the number of times given element present in the list.
- count(ele)
a = [“ABC”,”abc”,33,22,11,33]
print(a.count(“abc”))
print(a.count(33))
print(a.count(99))
7. Sorting (sorted() built in function. not change in list it return new list)
- sort() is used to sort the given list in ascending or descending order.
- sort(key=..,reverse=..) //key= it is a function that give a key to sort comparison, reverse= if it is true, return descending order list
- sort(),not return new list it do changes in list
a = [‘a’,’e’,’f’,’c’,’d’,’b’]
print(a.sort())
print(a)
a = [‘a’,’e’,’f’,’c’,’d’,’b’]
print(sorted(a))
print(a)
# sorting using custom key
employees = [
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000},
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]
# custom functions to get employee info
def get_name(employee):
return employee.get('Name')
def get_age(employee):
return employee.get('age')
def get_salary(employee):
return employee.get('salary')
# sort by name (Ascending order)
employees.sort(key=get_name)
print(employees, end='\n\n')
# sort by Age (Ascending order)
employees.sort(key=get_age)
print(employees, end='\n\n')
# sort by salary (Descending order)
employees.sort(key=get_salary, reverse=True)
print(employees, end='\n\n')
7. reverse()
- reverse() used to reverse the given list.
- It doesn’t return any value. it did changes in the existing list.
- reverse()
a = [‘a’,’e’,’f’,’c’,’d’,’b’]
print(a.reverse())
print(a)
8. copy()
- It returns the shallow copy of the list.
a = [‘a’,’e’,’f’,’c’,’d’,’b’]
b = a.copy()
b.append(‘m’)
print(a)
print(b)
List Comprehension
- This is the way to create a new list from the existing list.
- syntax:[expression for loop]
Write a program to get list square of number from 0 to 10
sqr_list = []
for x in range(1,11):
sqr_list.append(x*x)
#print("Square of {} is {}".format(x,x*x))
print(sqr_list)
print([x*x for x in range(1,11)])
a= ["Sagar","Sachin","Kedar","Ganesh","Ramesh"]
print([x[0] for x in a])
print([x[0].lower() for x in a])
print([(x[0].lower(),len(x)) for x in a])
print([x+y for x in ['Python ','C '] for y in ['Language','Programming']])
print([x+y for x in ['Python ','C ','Java '] if x != "Java " for y in ['Language','Programming']])
print([x+y for x in ['Python ','C ','Java '] if x != "Java " for y in ['Language','Programming'] if x != "C "])
Membership operator
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# Output: True
print('p' in my_list)
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)