Lists in Python

Lists in Python

Lists in Python are a collection of elements of different data types. Elements of a list are ordered implying that they will be displayed in the same order as they are created. They are mutable implying that they can be modified by adding or deleting elements.

 

 

Creating Lists in Python

Lists can be created by separating its elements with comma and enclosing them in square brackets. It can also be created using list() function.

 

# Python program to exemplify list creation

list1=[1,2,3,4,5]
print(list1)

list2=list((34,67,"Hi"))
print(list2)

Output:

[1, 2, 3, 4, 5]
[34, 67, 'Hi']

 

 

List Comprehension

List comprehension is another way of list creation in Python. Lists are created using another iterable and is done in fewer lines of codes. Iterable used here can be any one of lists, tuples, sets, strings and dictionary, etc. An iterable generated using range() function can also be used. Syntax of list creation using list comprehension is:

Syntax of List Comprehension:

#syntax of list comprehension 
list = [modify_func(i) for i in iterable if filters]

#which is equivalent to...
for i in iterator:
  if filters:
    list.append(modify_func(i))

Example of List Comprehension:

#creating list of cubes of natural numbers
MyRange = range(1,6)
NewList = [i**3 for i in MyRange]
print(NewList)

#creating list of even numbers
MyTuple = (1, 2, 3, 4, 5, 6, 7, 8)
NewList = [i for i in MyTuple if i%2==0]
print(NewList)

#creating list of lists where every list will have a number, its square and its cube
MyList = [1, 2, 3, 4, 5]
NewList = [[i, i*i, i*i*i] for i in MyList]
print(NewList)

#creating list of characters (in lowercase) of a string 
MyString = 'HeLLo'
NewList = [i.lower() for i in MyString]
print(NewList)

#creating a list containing element length of a set
MySet= ('jolie', 'evan', 'katia', 'marcus')
NewList = [len(i) for i in MySet]
print(NewList)

Output:

[1, 8, 27, 64, 125]
[2, 4, 6, 8]
[[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125]]
['h', 'e', 'l', 'l', 'o']
[5, 4, 5, 6]

 

 

Access Elements of Lists in Python

Elements of a list can be obtained using indexing where index numbers can be both positive and negative in Python. Positive index returns the element from the beginning of the list according to the number and negative index returns the element from the ending of the list according to the number. Negative index starts from -1 and positive index starts from 0.

 

# Python program to exemplify element accessing in a list

var_list=[23,45,78,25]
print(var_list[0])
print(var_list[-1])

Output:

23
25

 

 

Access Range of Elements of Lists in Python

Range of elements of a list can be obtained using index slicing which is specified like [start_index:end_index] where start_index is included and end_index is not included.

 

# Python program to exemplify accessing of range of elements of a list

var_list=[23,45,78,25]
print(var_list[0:2])
print(var_list[-2:])

Output:

[23, 45]
[78, 25]

 

 

Modify value of an Element of a List

Element of a list can be modified since it is mutable and modification is simply done by assigning new value to an old value using assignment operator.

 

# Python program to exemplify element modification in a list

var_list=[23,45,78,25]
print("Element at index 1 before modification: ",var_list[1])

var_list[1]=8

print("Element at index 1 after modification: ",var_list[1])

Output:

Element at index 1 before modification:  45
Element at index 1 after modification:  8

 

 

Add Elements in Lists in Python

New elements in a list can be added by using two functions:

  • append() – adds an element at the end of a list
  • insert() – adds an element at a particular position in a list specified by an index
# Python program to exemplify adding elements in a list

var_list=[23,45,78,25]

# adding element at the end of list using append()
var_list.append(98)
print(var_list)

# adding element at index 3 using insert() where first
# argument takes index and second argument takes the new element
var_list.insert(3,28)
print(var_list)

Output:

[23, 45, 78, 25, 98]
[23, 45, 78, 28, 25, 98]

 

 

Delete Elements of a List

Elements of a list can be deleted in the following ways provided below:

  • remove() – deletes first occurrence of a mentioned element from the list
  • pop() – deletes element at mentioned index and if not mentioned, then the last element is deleted
  • clear() – deletes all elements of a list and makes it empty []
  • del – deletes an element or range of elements or the entire list
# Python program to exemplify deleting elements of a list

var_list=[23,45,78,25]
print(var_list)

# deleting element using remove()
var_list.remove(45)
print(var_list)

# deleting element using pop()
var_list.pop()
print(var_list)

# deleting entire list using clear()
var_list.clear()
print(var_list)

Output:

[23, 45, 78, 25]
[23, 78, 25]
[23, 78]
[]

 

 

List Length

Length of a list can be obtained by using the len() function.

 

# Python program to exemplify deleting elements of a list

var_list=[23,45,78,25]
print(var_list)

length=len(var_list)
print(length)

Output:

[23, 45, 78, 25]
4

 

 

Check an Element in a List

To check if an object is an element of a list, if statement is used along with in operator. 

 

# Python program to exemplify if an object is an element of a list

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
if 'Saturday' in days:
  print('Yes, Saturday is an element of days.')
else:
  print('No, Saturday is not an element of days.')

Output:

Yes, Saturday is an element of days.

 

 

Copy of a List

There are several ways by which a copy of a list can be created and they are:

  • = operator – Creates a reference of the list. This means that changes made to the list by any of the reference variables will be done on the same list.
  • copy() – Creates an independent copy of the list. Changes made to the copy does not affect the original list.
  • list() – Creates an independent copy of the list. Changes made to the copy does not affect the original list.
# Python program to exemplify creating copy of a list

numbers = [1, 2, 3]
myNumbers = numbers
yourNumbers = numbers.copy()
hisNumbers = list(numbers)

print(myNumbers)     
print(yourNumbers)   
print(hisNumbers, "\n")    

#delete last element in 'numbers'
numbers.pop()       

print(myNumbers)     
print(yourNumbers)   
print(hisNumbers)

Output:

[1, 2, 3]
[1, 2, 3]
[1, 2, 3] 

[1, 2]
[1, 2, 3]
[1, 2, 3]

 

 

Joining Lists

There are several ways by which lists can be joined together and they are:

  • + operator – Joins two lists together into a new list
  • append() – appends all elements on one list into another using a looping mechanism
  • extend() – adds all elements of a list to another
# Python program to exemplify joining of two lists in Python

colors = ['Red', 'Blue', 'Yellow']
numbers = [1, 2]
mylist = colors + numbers
print(mylist)

colors = ['Orange', 'White', 'Green']
numbers = [12, 25]
# elements of list numbers being added to the list colors
for i in numbers:
  colors.append(i)
print(colors)

colors = ['Pink', 'Gray', 'Black']
numbers = [90, 65]
colors.extend(numbers)
print(colors)

Output:

['Red', 'Blue', 'Yellow', 1, 2]
['Orange', 'White', 'Green', 12, 25]
['Pink', 'Gray', 'Black', 90, 65]

 

Share this post

Leave a Reply

Your email address will not be published.