lists in python | Python Lists

By | December 25, 2019

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.

lists in Python

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.

example:

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]

List Methods:

These are the methods which are used with list in Python.

  • index()
  • count()
  • append()
  • remove()
  • reverse()

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

Example:

If there is a list myList = [1,2,3,4,5]

myList.index(3)
myList.count()
myList.append(6)
myList.remove(4)
myList.reverse()

Slicing and Dicing

Slicing: means that selecting multiple elements from the list.

myList[start:end]

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”]

x[1:3]

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.

Leave a Reply

Your email address will not be published. Required fields are marked *