You are on page 1of 16

CSE 1001 (Python)

Faculty Name: Dr. AMIT


KUMAR TYAGI
Lists
 The simplest data structure in Python and is used to store a list of values.
 Lists are collections of items (strings, integers, or even other lists).
 Each item in the list has an assigned index value.
 Lists are enclosed in [ ]
 Each item in a list is separated by a comma
 Unlike strings, lists are mutable, which means they can be changed.

List Creation
 Lists are created using a comma separated list of values surrounded by
square brackets.
 Lists hold a sequence of values (just like strings can hold a sequence of
characters).
 Lists are very easy to create, these are some of the ways to make lists

An empty list is created using just square brackets:

emptyList = [ ]

list1 = ['one’, ‘two’, ‘three’, ‘four’, ‘five']

numlist = [1, 3, 5, 7, 9]

mixlist = ['yellow', 'red', 'blue', 'green', 'black', 1, 10]

List Length
 With the length function we can get the length of a list

list = ["1", "hello", 2, "world"]

len(list)

>>4
List Append
 List append will add the item at the end.
 If you want to add at the beginning, you can use the insert function (see
below)

list.insert(0, "Files")

list = ["Movies", "Music", "Pictures"]

list.append(x) will add an element to the end of the list

list.append("Files")

print (list)

['Movies', 'Music', 'Pictures', 'Files']

List Insert
The syntax is: list.insert(x, y) #will add element y on the place before x

list = ["Movies", "Music", "Pictures"]

list.insert(2,"Documents")

print list

['Movies', 'Music', 'Documents', 'Pictures', 'Files']

You can insert a value anywhere in the list

list = ["Movies", "Music", "Pictures"]

list.insert(3, "Apps")
List Remove
To remove an element's first occurrence in a list, simply use list.remove

The syntax is: list.remove(x)

List = ['Movies', 'Music', 'Files', 'Documents', 'Pictures']

list.remove("Files")

print (list)

['Movies', 'Music', 'Documents', 'Pictures']

a = [1, 2, 3, 4]

a.remove(2)

print a

[1, 3, 4]

List Extend
The syntax is: list.extend(x) #will join the list with list x

list2 = ["Music2", "Movies2"]

list1.extend(list2)

print list1

['Movies', 'Music', 'Documents', 'Pictures', 'Music2', 'Movies2']

NOTE: A list is an object. If you append another list onto a list, the second list will be
a single object at the end of the list.

my_list = ['geeks', 'for', 'geeks']

another_list = [6, 0, 4, 1]
my_list.append(another_list)

print my_list

['geeks', 'for', 'geeks', [6, 0, 4, 1]]

my_list = ['geeks', 'for']

another_list = [6, 0, 4, 1]

my_list.extend(another_list)

print my_list

['geeks', 'for', 6, 0, 4, 1]

NOTE: A string is an iterable, so if you extend a list with a string, you’ll append
each character as you iterate over the string.

my_list = ['geeks', 'for', 6, 0, 4, 1]

my_list.extend('geeks')

print my_list

['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']

List Delete
Use del to remove item based on index position.

list = ["Matthew", "Mark", "Luke", "John"]

del list[1]

print list

>>>Matthew, Luke, John


List Keywords
The keyword "in" can be used to test if an item is in a list.

list = ["red", "orange", "green", "blue"]

if "red" in list:

do_something()

#Keyword "not" can be combined with "in".

list = ["red", "orange", "green", "blue"]

if "purple" not in list:

do_something()

List Reverse
The reverse method reverses the order of the entire list.

L1 = ["One", "two", "three", "four", "five"]

#To print the list as it is, simply do:

print L1

#To print a reverse list, do:

for i in L1[::-1]:

print i

#OR

L = [0, 10, 20, 40]

L.reverse()

print L

[40, 20, 10, 0]


List Sorting
 The easiest way to sort a List is with the sorted(list) function.
 That takes a list and returns anew list with those elements in sorted order.
 The original list is not changed.
 The sorted() function can be customized though optional arguments.
 The sorted() optional argument reverse=True, e.g. sorted(list,
reverse=True),
 makes it sort backwards.

#create a list with some numbers in it

numbers = [5, 1, 4, 3, 2, 6, 7, 9]

#prints the numbers sorted

print sorted(numbers)

#the original list of numbers are not changed

print numbers

my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "EE"]

#if no argument is used, it will use the default (case sensitive)

print (sorted(my_string))

#using the reverse argument, will print the list reversed

print (sorted(strs, reverse=True)) ## ['zz', 'aa', 'CC', 'BB']

This will not return a value, it will modify the list

list.sort()
List Split
Split each element in a list.

mylist = "one;two;three;four,five;1;2"

newlist = mylist.split(';')

print (newlist)

['one', 'two', 'three', 'four,five', '1', '2']

List Indexing
Each item in the list has an assigned index value starting from 0.

Accessing elements in a list is called indexing.

list = ["first", "second", "third"]

list[0] == "first"

list[1] == "second"

list[2] == "third"

List Slicing
 Accessing parts of segments is called slicing.
 Lists can be accessed just like strings by using the [ ] operators.
 The key point to remember is that the :end value represents the first value
that is not in the selected slice.
 So, the difference between end and start is the number of elements selected
 (if step is 1, the default).

Let's create a list with some values in it

colors = ['yellow', 'red', 'blue', 'green', 'black']


print colors[0]

>>> yellow

print colors [1:]

>>> red, blue, green, black

Let's look at this example taken from this stackoverflow post.

a[start:end] # items start through end-1

a[start:] # items start through the rest of the array

a[:end] # items from the beginning through “end-1”

a[:] # a copy of the whole array

There is also the step value, which can be used with any of the above

a[start:end:step] # start through not past end, by step

The other feature is that start or end may be a negative number, which means it
counts from the end of the array instead of the beginning.

a[-1] # last item in the array

a[-2:] # last two items in the array

a[:-2] # everything except the last two items

List Loops
When using loops in programming, you sometimes need to store the results of the

loops.

One way to do that in Python is by using lists.


This short section will show how you can loop through a Python list and process

the list items.

#It can look something like this:

matching = []

for term in mylist:

do something

#For example, you can add an if statement in the loop, and add the item to the
(empty) list

if it's matching.

matching = [] #creates an empty list using empty square brackets []

for term in mylist:

if test(term):

matching.append(term)

#If you already have items in a list, you can easily loop through them like this:

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

for i in items:

print (i)

List pop
The pop() method removes the specified index, (or the last item if index is
not specified):

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)
List Clear
The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)

List constructor
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double


round-brackets
print(thislist)

List count
The count() method returns the number of elements with the specified value.

points = [1, 4, 2, 9, 7, 8, 9, 3, 1]

x = points.count(9)

List copy
The copy() method returns a copy of the specified list.

fruits = ['apple', 'banana', 'cherry', 'orange']

x = fruits.copy()
List Methods
Calls to list methods have the list they operate on appear before the method name.

Any other values the method needs to do its job is provided in the normal way as

an extra argument inside the round brackets.

s = ['h','e','l','l','o'] #create a list

s.append('d') #append to end of list

len(s) #number of items in list

s.sort() #sorting the list

s.reverse() #reversing the list

s.extend(['w','o']) #grow list

s.insert(1,2) #insert into list

s.remove('d') #remove first item in list with value e

s.pop() #remove last item in the list

s.pop(1) #remove indexed value from list

s.count('o') #search list and return number of instances found

s = range(0,10) #create a list over range

s = range(0,10,2) #same as above, with start index and increment

List Examples

First, create a list containing only numbers.

list = [1,2,3,5,8,2,5.2] #creates a list containing the values 1,2,3,5,8,2,5.2

i=0

while i < len(list): #The while loop will print each element in the list
print list[i] #Each element is reached by the index (the letter in the
square bracket)

i=i+1 #Increase the variable i with 1 for every time the while
loop runs.

The next example will count the average value of the elements in the list.

list = [1,2,3,5,8,2,5.2]

total = 0

i=0

while i < len(list):

total = total + list[i]

i=i+1

average = total / len(list)

print average

List Comprehensions
List comprehensions provide a concise way to create lists.

It consists of brackets containing an expression followed by a for clause, then

zero or more for or if clauses. The expressions can be anything, meaning you can

put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression in the

context of the for and if clauses which follow it.


The list comprehension always returns a result list.

If you used to do it like this:

new_list = []

for i in old_list:

if filter(i):

new_list.append(expressions(i))

You can obtain the same thing using list comprehension:

new_list = [expression(i) for i in old_list if filter(i)]

The basic syntax is

[ expression for item in list if conditional ]

This is equivalent to:

for item in list:

if conditional:

expression

new_range = [i * i for i in range(5) if i % 2 == 0]

Which corresponds to:

*result* = [*transform* *iteration* *filter* ]

The * operator is used to repeat. The filter part answers the question if the

item should be transformed.


Let's start easy by creating a simple list.

x = [i for i in range(10)]

print x

# This will give the output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Sample problems

1) Sort the given list of elements using bubble sort


2) Find the largest and smallest element from the list
3) Print the even no’s using list Comprehensions
4) Delete elements whose indexed is multiple of 3 from a given list of 20
elements

Write a Python program to sum all the items in a list.

def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))

Find the largest element from the list

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
Write a Python program to get a list, sorted in increasing order by the last element in each
tuple from a given list of non-empty tuples.

def last(n): return n[-1]

def sort_list_last(tuples):
return sorted(tuples, key=last)

print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

Write a Python program to remove duplicates from a list.

a = [10,20,30,20,10,50,60,40,80,50,40]

dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)

print(dup_items)

Write a Python program to print the numbers of a specified list after removing
even numbers from it.

num = [7,8, 120, 25, 44, 20, 27]


num = [x for x in num if x%2!=0]
print(num)

Example: Find list on Moodle.

You might also like