Python 3x Pandas Django

Lists


Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data.

Lists are created using square brackets [ ]

Lists are ordered, mutable & indexed

mylist = ["red", "green", "blue"]
print(mylist)   #Output: ['red', 'green', 'blue']

List Items

mylist = ["red", "green", "blue"]
print(mylist[0])  #Output: red
print(mylist[1])  #Output: green
print(mylist[2])  #Output: blue

Mutable

The list is mutable, that we can change, add, and remove items in a list after it has been created.

thislist = ["apple", "banana", "cherry"]
print(thislist)             #Output: ['apple', 'banana', 'cherry']
thislist[0] = "mango"
thislist[1] = "Strawberry"
thislist.insert(2, "mango")

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["Mango", "Strawberry"]
print(thislist)              #Output: ['apple', 'Mango', 'Strawberry']

thislist = ["apple", "banana", "cherry"]
thislist.append("mango")     #append() method is used to add an item to the end of the list
print(thislist)              #Output: ['apple', 'banana', 'cherry', 'mango']

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, " mango") #insert() method is used to insert an item at a specified index.
print(thislist)              #Output: ['apple', ' mango', 'banana', 'cherry']

Run code snippet

List Items - Data Types

A list can contain different data types

List1 = ["apple", 1, "banana", 2, "cherry", 3.5, True, False]
print(List1)  #Output ['apple', 1, 'banana', 2, 'cherry', 3.5, True, False]

list() Constructor

Using the list() constructor to make a List

thislist = list(("apple", "banana", "cherry"))
print(thislist)   #Output: ['apple', 'banana', 'cherry']

Accessing an Items

List items are indexed and you can access them by referring to the index number

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]

image missing

Syntax

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]
# Indexing
print(thislist[0]) #Output: Leo
print(thislist[1]) #Output: Matt
print(thislist[2]) #Output: Kane
print(thislist[3]) #Output: Scott
print(thislist[4]) #Output: Peter
print(thislist[5]) #Output: Will

# Negative Indexing
print(thislist[-6]) #Output: Leo
print(thislist[-5]) #Output: Matt
print(thislist[-4]) #Output: Kane
print(thislist[-3]) #Output: Scott
print(thislist[-2]) #Output: Peter
print(thislist[-1]) #Output: Will

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

The returned value will include the specified start index and it exclude the specified end index.

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]

print(thislist[2:5]) #Output: ["Kane", "Scott", "Peter"]

Start index: 2

End index: 5

Index 2, Kane is included and index 5, will not included

Remember that the start\first item has index 0

By leaving out the start value, the range will start at the first item:

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]
print(thislist[:4]) #Output: ['Leo', 'Matt', 'Kane', 'Scott']

By leaving out the end value, the range will go on to the end of the list:

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]
print(thislist[2:]) #Output: ['Kane', 'Scott', 'Peter', 'Will']

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

thislist = ["Leo", "Matt", "Kane", "Scott", "Peter", "Will"]
print(thislist[-4:-1]) #Output: ['Kane', 'Scott', 'Peter']

Start index: -4

End index: -1

Index -4, Kane is included and index -1, will not included

Remember that the start\first item has negative index -1

List Copy

mylist = ["Matt", "Kane", "Scott", "Peter", "Will"]
newlist = mylist

newlist[0] = "Leo"

print(mylist)   #Output: ['Leo', 'Kane', 'Scott', 'Peter', 'Will']
print(newlist)  #Output: ['Leo', 'Kane', 'Scott', 'Peter', 'Will']

did you notice the output? both mylist and newlist prints the same set of items because we have used equal sign(=) for creating a newlist, which means both these lists stored in the same memory on your computer. When we change a newlist element and it will also update the mylist as it pointing to the same memory.

So, the best way to copy the list using slicing and list method copy()

mylist = ["Matt", "Kane", "Scott", "Peter", "Will"]

newlist1 = mylist[:]
newlist1[0] = "Leo"

newlist2 = mylist.copy() #List Method
newlist2[0] = "Leo"

print(mylist)    #Output:['Matt', 'Kane', 'Scott', 'Peter', 'Will']
print(newlist1)  #Output:['Leo', 'Kane', 'Scott', 'Peter', 'Will']
print(newlist2)  #Output:['Leo', 'Kane', 'Scott', 'Peter', 'Will']

Some Important List Methods

List gets really more powerful when it comes to list methods instead of inbuilt functions

Method Description
append() append object to end
clear() removes all the elements from the list
copy() returns a copy of the list
count() returns the number of occurrence of the specified value
extend() extend the list by appending the given list at the end
index() returns the index of the first element with the specified value \ returns the index of the specified value for the specified start & stop index
insert() insert an element at the specified index
pop() removes the element at the end of the list / at the specified index
remove() removes the first item in the list with the specified value
reverse() reverses the order of the list
sort() sorts the list

append()

append the item\object to end.

number_lists = [1,2,3,4,5]

number_lists.append(6)
print(number_lists)   #Output: [1, 2, 3, 4, 5, 6]


insert()

insert an element at the specified index.

number_lists = [1,2,3,4,5]

number_lists.insert(1,6)
print(number_lists)   #Output: [1, 6, 2, 3, 4, 5]


extend()

extend the list by appending the given list at the end.

number_lists = [1,2,3,4,5]

number_lists.extend([6,7,8,9,10])
print(number_lists)   #Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


pop()

removes the element at the end of the list / at the specified index.

number_lists = [1,2,3,4,5]

number_lists.pop()
print(number_lists)   #Output: [1,2,3,4]

number_lists = [1,2,3,4,5]

number_lists.pop(1)
print(number_lists)   #Output: [1,3,4,5]


remove()

removes the first item in the list with the specified value.

number_lists = [1,2,3,4,5,1]

number_lists.remove(1)
print(number_lists)   #Output: [2,3,4,5,1]


clear()

removes all the elements from the list/

number_lists = [1,2,3,4,5,1]

number_lists.clear()
print(number_lists)   #Output: []


index()

returns the index of the first element with the specified value

Syntax

mylists.index(value,start_index(optional),end_index(optional))

Example

number_lists = [1,2,3,4,5,1]

return_index1 = number_lists.index(1)
print(return_index1)    #Output: 0

return_index2 = number_lists.index(1,3,6)
print(return_index2)    #Output: 5

return_index3 = number_lists.index(1,3,)
print(return_index3)    #Output: 5


in Keyword

The in keyword has two purposes:

1. To check if a value is present in a list, tuple, range, string, etc. and it returns boolen values

2. To iterate through a sequence in a for loop.

# For Lists
number_lists = [1,2,3,4,5,1]
x = 1
print(x in number_lists)            #Output: True

# For Strings
my_string = "mystring"
x = 's'
print(x in my_string)               #Output: True


count()

returns the number of occurrence of the specified value

number_lists = [1,2,3,4,5,1]

print(number_lists.count(3))       #Output: 1
print(number_lists.count(1))       #Output: 2


sort() vs sorted()

Both do the sorting action but sorted create a new list and return, sort modify the original list and do not return

number_lists = [1,2,4,3,5,1]

print(sorted(number_lists))      #Output: [1, 1, 2, 3, 4, 5]   #Create a new sorted array and return
print(number_lists)              #Output: [1, 2, 4, 3, 5, 1]   #Do not change the original list

print(number_lists.sort())       #Output: None                 #Modify the original list and return None
print(number_lists)              #Output: [1, 2, 4, 3, 5, 1]   #Modify the original list


revese()

reverse the order of the list

number_lists = [1,2,4,3,5,1]

number_lists.reverse()
print(number_lists)         #Output: [1, 5, 3, 4, 2, 1]


Some Common List Patterns


range() + list()

range() function returns a sequence of numbers, starting from 0(by default), and increments by 1 (by default), and stops before a specified number.

print(range(100))  #Output: range(0, 100)

You will not see a sequence of number

print(list(range(100)))
print(list(range(0, 100)))

When you use list() constructor, you will see the sequence of numbers starts from 0 (by default) and end with 99 (before the given value) in list type

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 99]


join()

join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.

Syntax

string_name.join(iterable)

string_name: It is the name of string in which joined elements of iterable will be stored.

Example

string_name = "?"
iterable = ["Hi,", "my", "name", "is", "John"]

#Joined the element of iterable object with the specified delimiter
new_str = string_name.join(iterable)
print(new_str)          #Output: Hi,?my?name?is?John

string_name = " "
iterable = ["Hi,", "my", "name", "is", "John"]

#Joined the element of iterable object with the specified delimiter
new_str = string_name.join(iterable)
print(new_str)          #Output: Hi, my name is John


List Unpacking

Unpacking in python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement by using the iterable unpacking operator, *

#Example 1
a, b, c = [1, 2, 3]
print(a)
print(b)
print(c)

#Example 2
a, b, c, *others = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(others)

#Example 2
a, b, c, *others, d= [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(others)
print(d)

Try it yourself

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!