Monday, August 23, 2021

Python - Lists

 Python Lists



Earlier when discussing strings we introduced the concept of a sequence in Python

  • Lists can be thought of as the most general version of a sequence in Python.
  • Unlike strings, they are mutable, meaning the elements inside a list can be changed!
  • Lists are constructed with brackets "[ ]" and commas separating every element in the list.


The list is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. An important thing about a list is that items in a list need not be of the same type.

Example: 

list1 = ['Maths', 'manoj', 1993, 2021];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]


List Indexing:

  • Indexing work just like in strings.
  • A list index refers to the location of an element in a list.
  • Remember the indexing begins from 0 in Python.
  • The first element is assigned an index 0, the second element is assigned an index of 1, and so on and so forth.

L = ['State', 'India', 'Hello!']
Python ExpressionResultsDescription
L[2]Hello!Offsets start at zero
L[-2]IndiaNegative: count from the right
L[1:]['India', 'Hello!']Slicing fetches sections


List Slicing:

  • We can use a : to perform slicing which grabs everything up to a designated point.
  • The starting index is specified on the left of the : and the ending index is specified on the right of the :.
  • Remember the element located at the right index is not included.



Python


List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.


Python ExpressionResultsDescription
len([1, 2, 3,4,5])5Length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
['12'] * 4['12', '12', '12', '12']Repetition
2 in [1, 2, 3]TrueMembership
for x in [1, 2, 3,4]
 print(x)
1 2 3 4

Iteration


List Functions:

len()

  • len() the function returns the length of the list.

min()

  • min() the function returns the minimum element of the list
  • min() function only works with lists of similar data types

max()

  • max() the function returns the maximum element of the list
  • max() function only works with lists of similar data types

sum()

  • sum() the function returns the sum of the elements of the list
  • sum() function only works with lists of numeric data types

sorted()

  • sorted() the function returns the sorted list
  • sorted() the function takes reverse boolean as an argument
  • sorted() function only works on a list with similar data types

Python ExpressionResultsDescription
len([1, 2, 3,4,5])5Length
min([1, 2, 3,4,5])small number in list
max(['Argue','Burglar','Parent','Linear','shape'])'shape'maximum element in list
sum([6,9,1,3,5.5])24.5sum of all elements in the list
sorted([6,9,1,3,5.5])[1, 3, 5.5, 6, 9]

sorted list

List Methods:

  • If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python, however, tend to be more flexible than arrays in other languages for two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
  • Let's go ahead and explore some more special methods for lists:

append()

  • Use the append() method to permanently add an item to the end of a list.
  • append() the method takes the element which you want to add to the list as an argument

Example:
list = [1, 2, 3, 1, 1, 1, 3, 10, 5, 8]
list = list.append('Append!')
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append!']


extend()

  • Use the extend() method to merge a list to an existing list.
  • extend() the method takes a list or any iterable(don't worry about it now) as an argument.
  • Quite helpful when you have two or more lists and you want to merge them together.
Example:

list = [1, 2, 3, 1, 1, 1, 3, 10, 5, 8]

list = list.extend(['cuba','france','India'])
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']


pop()

  • Use pop() to "pop-off" an item from the list.
  • By default pop() takes off the element at the last index, but you can also specify which index to pop off.
  • pop() takes the index as an argument and returns the element which was popped off.


Example:
list =  [1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']
list = list.pop() # 0th index
print(list)

Results:
'India'


remove()

  • Use remove() to remove an item/element from the list.
  • By default "remove()"removes the specified element from the list.
  • remove() takes the element as an argument.


Example:
list =  [1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']
list = list.remove('cuba')
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'france','India']


count()

  • The count() the method returns the total occurrence of a specified element in the list.


Example:
list = [2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append', 'cuba','france','India','cuba']
list = list.count('cuba') # Count the number of times element  occurs in the list
print(list)

Results:
2


index()

  • The index() the method returns the index of a specified element in the list.


Example:

list = [2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append!', 'cuba','france','India']
list = list.index('cuba')
print(list)

Results:
10


sort()

  • Use sort() to sort the list in either ascending/descending order.
  • The sorting is done in ascending order by default.
  • sort() the method takes the reverse boolean as an argument.
  • sort() the method only works on a list with elements of the same data type.


Example:

list = [6, 9, 1, 3, 5]
list.sort()
print(list)

Results:
[1, 3, 5, 6, 9]



reverse()

  • reverse() method reverses the list elements.


Example:
list = [1, 1, 1, 1, 1.43, 2, 3, 3, 5, 8, 10, 'cuba', 'france']
list.reverse()
print(list)

Results:

['france', 'cuba', 10, 8, 5, 3, 3, 2, 1.43, 1, 1, 1, 1]



Nested Lists:

  • A great feature of Python data structures is that they support nesting. This means we can have data structures within data structures. For example A list inside a list.

Example:
list_1 = [1,2,3]
list_2 = ['b','a','d']
list_3 = [7,8,9]

list_of_lists  =  [list_1,list_2,list_3] # Make a list of lists to form a matrix
print(list_of_lists)

Results:
[[1, 2, 3], ['b', 'a', 'd'], [7, 8, 9]]

This is all about List in Python...



You can also read the below links...





No comments:

Post a Comment

Python - Conditional statements ,if condition in python

 Python - if - Conditional statements What is the if condition in python? Decision-making is the anticipation of conditions occurring while ...