lists in Python contain any type but a list is also a Python type. and a list can also contain a list.
A list contains any Python type means you can store any type of data in it e.g strings booleans and floats etc.
Lists are used for storing values of different datatypes rather than creating a bunch of variables for it.
Examples of List:
If you want to store the height of your family members. Then you can store all the values.
Each will be separated with commas and assign to a single variable and surrounded by square brackets
it means that you can store values of multiple datatype variables in a single variable.
familyHeights = ["kelly" , 1.1 , "merry" , 2.2 , "belly" , 3.2 , "lolly" , 4.5]
above is the example of a list
You can also create a list in the following manner and you can understand it easily. create a separate list and separate it by comma
familyHeights = [["kelly", 1.1], ["merry", 2.2], ["belly", 3.2], ["lolly", 4.5] ]
Examples of Lists in Python
[1, 3, 4, 2] out put [1, 3, 4, 2] [[1, 2, 3], [4, 5, 7]] [[1,2,3], [4,5,7]] [1+2,"a"*5, 3] out put [3, 'aaaaa', 3]
These are the methods which are used with list in Python.
index() method that used with object list that gives index of element in that list
count() This method helps to count the number of elements in a list.
append() Add an elements at the end of a list
remove() That helps to delete the elements from the list
reverse() That helps to reverse the order of a list
If there is a list myList = [1,2,3,4,5]
Slicing and Dicing
Slicing: means that selecting multiple elements from the list.
Start index will be includes while the end index will not be included in your list.
if there is a list
x = [“a”,”b”,”c”,”d”]
This will print the value b and c
becuase index 1 and 2 is included and 3 is excluded.
x[:2] if you not specified the starting index then slicing will print all the elements from starting.
x[2:] If you not specified the ending ending index the slicing will print elements untill end of the list.
x[:] If you not specified both the starting and ending index then all the elements of the list will be printed.