Python List
In Python, an object of list data type can be a collection of many data types. Python lists have following basic properties:
- Ordered collections of arbitrary objects
From a functional view, lists are just places to collect other objects Lists also maintain a left-toright positional ordering among the items contained in them (i.e., they are sequences). - Accessed by offset
A component object of list can be accessed by its position. - Variable-length, heterogeneous, and arbitrarily nestable
Unlike strings, lists can grow and shrink in place (their lengths can vary), and they can contain any sort of object, not just one-character strings (they‘re heterogeneous). Because lists can contain other complex objects, they also support arbitrary nesting. - Of the category “mutable sequence”
Lists are mutable (i.e., can be changed in place) and can respond to all the sequence operations used with strings, such as indexing, slicing, and concatenation. In fact, sequence operations work the same on lists as they do on strings; the only difference is that sequence operations such as concatenation and slicing return new lists instead of new strings when applied to lists. Because lists are mutable, however, they also support other operations that strings don‘t, such as deletion and index assignment operations, which change the lists in place.
>>> L = [‘spam’, ‘Spam’, ‘SPAM!’]
>>> L[2] # Offsets start at zero ‘SPAM!’
>>> L[−2] # Negative: count from the right ‘Spam’
>>> L[1:] # Slicing fetches sections [‘Spam’, ‘SPAM!’]
>>> L = [1, 2, 3]
>>> L[1:2] = [4, 5] # Replacement/insertion
>>> L
[1, 4, 5, 3]
>>> L[1:1] = [6, 7] # Insertion (replace nothing)
>>> L
[1, 6, 7, 4, 5, 3]
>>> L[1:2] = [ ] # Deletion (insert nothing)
>>> L
[1, 7, 4, 5, 3]
>>> L = [1]
>>> L[:0] = [2, 3, 4] # Insert all at :0, an empty slice at front
>>> L
[2, 3, 4, 1]
>>> L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty slice at end
>>> L
[2, 3, 4, 1, 5, 6, 7]
>>> L.extend([8, 9, 10]) # Insert all at end, named method
>>> L
[2, 3, 4, 1, 5, 6, 7, 8, 9, 10]
List Method Calls
>>> L = [‘THIS’, ‘IS’, ‘COMPUTER’]
>>> L.append(‘PROGRAMMING’) # Append method call: add item at end
>>> L
[‘THIS’, ‘IS’, ‘COMPUTER’, ‘PROGRAMMING’]
>>> L.sort()
>>> L
[‘COMPUTER’, ‘IS’, ‘PROGRAMMING’, ‘THIS’]
>>> L = [1, 2]
>>> L.extend([3, 4, 5]) # Add many items at end (like in-place +)
>>> L
[1, 2, 3, 4, 5]
>>> L.pop() # Delete and return last item (by default: −1) 5
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result (iterator)
[1, 2, 3, 4]
List Practice Codes
Q1. From given list:
gadgets = [‘Mobile’, ‘Laptop’, 100, ‘Camera’, 310.28, ‘Speakers’, 27.00, ‘Television’, 1000, ‘Laptop Case’, ‘Camera Lens’]
a) Create separate lists of strings and numbers.
b) Sort the strings list in ascending order.
c) Sort the strings list in descending order.
d) Sort the number list from lowest to highest.
e) Sort the number list from highest to lowest
gadgets = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00, "Television", 1000, "Laptop Case", "Camera Lens"] s = [] n = [] for i in gadgets: if type(i) == float or type(i) == int: n.append(i) n.sort() else: s.append(i) s.sort() print('In ascending order and from lowest to highest\n',s,'\n',n) s.reverse() n.reverse() print('In descending order and from highest to lowest\n',s,'\n',n)
Q2. Produce a code to get first, second best scores from the list
L= [86,86,85,85,85,83,23,45,84,1,2,0].
L=[86,86,85,85,85,83,23,45,84,1,2,0] L.sort() print("First best score = ", L[-1]) L.pop() print("Second best score = ", L[-1])
Q3. Write code to add up and print all the positive values in a list of integers. The code prints zero if the list is empty.
lst = [3, -3, 5, 2, -1, 2] sum = 0 if len(lst) = 1: for i in lst: if i = 1: sum += i print(f'Sum: {sum}')
Q4. Write code that counts and prints the even numbers in a list of integers. The code prints zero if the list is empty.
my_list = [3, 5, 4, -1, 9, 8, 2] even_count = 0 for num in my_list: if num % 2 == 0: even_count += 1 print(f'Even numbers in the given list are {even_count}')
Q5. Write code that accepts two parameters, a list of numbers and a number x. The code should print, in order, all the elements in the list that are at least as large as the number x.
def elements_larger_or_equal(lst, x): lst.sort() for num in lst: if num = x: print(num) elements_larger_or_equal([3, 5, 4, 10, -1, 7], 3)
Split method
Q6. Give possible implementation for split method.
st = '' L = [] sep = ' ' s = input('Enter a sentence: ') for i in s: if i != sep: st+=i else: L.append(st) st = '' L.append(st) print(L)
Q7. Input a term(probably multi-word) from user and print it’s acronym.
acr = '' s = input('Enter a term: ') s = s.split() for i in s: acr += i[0] acr = acr.upper() print(f'Acronym: {acr}')
List Code For Matrices
Q8. Input a 3×3 matrix from the user in a list.
m=[] m_row=[] for i in range(3): for j in range(3): x=int(input(f'enter value of Row {i} and column {j}\n')) m_row.append(x) m.append(m_row) m_row=[] print(m)
Q9. Increment in a different matrix.
x=[] x_row=[] m=[[1, 2, 3], [4,5 , 6], [7, 8, 9]] for r in m: for c in r: x_row.append(c+1) x.append(x_row) x_row=[] print(x)
Q10. Increment in the same matrix.
x=[] x_row=[] m=[[1, 2, 3], [4,5 , 6], [7, 8, 9]] for i in range(len(m)): for j in range(len(m[i])): m[i][j]=m[i][j]+1 print(m)
Q11. Add two similar dimension matrices and store it in a new matrix.
m1=[[1, 2, 3], [4, 5 , 6], [7, 8, 9]] m2=[[2, 2, 2], [2, 2 , 2], [2, 2, 2]] m=[] for i in range(3): m_row = [] for j in range(3): x=m1[i][j]+m2[i][j] m_row.append(x) m.append(m_row) print(m)
Q12. Add two similar dimension matrices and store it in the same matrix.
m1=[[1, 2, 3], [4, 5 , 6], [7, 8, 9]] m2=[[2, 2, 2], [2, 2 , 2], [2, 2, 2]] for i in range(len(m1)): for j in range(len(m2)): m1[i][j ] = m1[i][j] + m2[i][j] print(m1)
Q13. Transpose of a matrix.
m1=[[1, 2, 3], [4, 5 , 6], [7, 8, 9]] m=[] m_row=[] for i in range(3): for j in range(3): x=m1[j][i] m_row.append(x) m.append(m_row) m_row = [] print(m)
Q14. Multiply two similar dimension matrices and store it in a new matrix.
m1=[[1, 2, 3], [4, 5 , 6], [7, 8, 9]] m2=[[2, 2, 2], [2, 2 , 2], [2, 2, 2]] m=[] m_row=[] for i in range(3): for j in range(3): x=m1[i][j]*m2[i][j] m_row.append(x) m.append(m_row) m_row=[] print(m)