Lists in Python

list is an ordered set of elements or values enclosed in a brackets. The elements or values are separated by commas ( , )

variable = [element1, element 2, element 3, ..., element N]

example

list22= [1,3,5,6,7,9]

a list can also have different type of data

mix = [3.14,99,"love"]

each element in the list can be accessed by using the index number, python has both normal and reverse index number, example for getting the last item in mix variable

mix[-1] #love

lists using range() function

we can use range( ) to create a list of certain range ,we should pass range function inside list function ,see example given below

listx = list(range(20, 60))

the above code writes 20 to 60 numbers into the listx variable

Appending to a List

we can append elements to already existed elements in the list variable by using .append( ) function

students = ["john","alex","noah"]
students.append("Turbo")
students.append("Jenny")
['john', 'alex', 'noah', 'Turbo', 'Jenny']

index in lists

mix[-1] #love

just like the strings, lists have indexes too, starts from 0, the first element will be zero and the last will be -1, we can access and modify any element because lists are mutable in python.

Lists are Mutable

the meaning of mutable is ,we can modify the list without creating a new list in process

members = ["zhong","boxboy","wiz"]
id(members)
members[0]="kayne"
id(members)
members
139890111034504 #id
139890111034504
['kayne', 'boxboy', 'wiz']

as you noticed above,the id will be same after modifying the 0th index element ,this is called mutable

List Slicing

by slicing the list, we can create new lists from existing list by slicing to certain index, we required,syntax is given below

list[start:end]

example

num = [344,4,5,54,2,67,24,27]
num[:]
num[:3]
num[2:]
num[3:6]
[344, 4, 5, 54, 2, 67, 24, 27]
[344, 4, 5]
[5, 54, 2, 67, 24, 27]
[54, 2, 67]
Last updated on by vishal devxo