0% found this document useful (0 votes)
3 views

Python Tutorial_ a Tutorial Lists

This document is a tutorial on list manipulation in Python, covering methods like append, pop, remove, and extend. It explains how to add, remove, and find elements in lists, as well as the performance implications of different list operations. The tutorial also includes examples and comparisons of methods to illustrate their usage and efficiency.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Tutorial_ a Tutorial Lists

This document is a tutorial on list manipulation in Python, covering methods like append, pop, remove, and extend. It explains how to add, remove, and find elements in lists, as well as the performance implications of different list operations. The tutorial also includes examples and comparisons of methods to illustrate their usage and efficiency.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Sequential Data Types: Lists and Strings


Next Chapter: Shallow and Deep Copy

Lists

Follow Bernd Klein,


the author of this
Changing lists website, at Google+:
Bernd Klein on
Python 3
Google
Tutorial This chapter of our tutorial deals with further aspects of lists. You will learn how to append and insert objects to lists and you will also learn how to delete and remove elements by
using 'remove' and 'pop'
Bernd Klein on
The Origins of Facebook
A list can be seen as a stack. A stack in computer science is a data structure, which has at least two operations: one which can be used to put or push data on the stack and
Python
another one to take away the most upper element of the stack. The way of working can be imagined with a stack of plates. If you need a plate you will usually take the most upper
Starting with
one. The used plates will be put back on the top of the stack after cleaning. If a programming language supports a stack like data structure, it will also supply at least two
Python: The Search this website:
operations:
Interactive Shell
Executing a push Go
Script This method is used to put a new object on the stack. Depending on the point of view, we say that we "push" the object on top or attach it to the right side. Python doesn't
Indentation offer - contrary to other programming languages - no method with the name "push", but the method "append" has the same functionality. This topic in German
pop / Deutsche
Data Types and
This method returns the most upper element of the stack. The object will be removed from the stack as well. Übersetzung: Listen
Variables
peek und Listen-
Operators Some programming languages provide another method, which can be used to view what is on the top of the stack without removing this element. The Python list class Manipulation
Sequential Data doesn't possess such a method, because it is not needed. A peek can be simulated by accessing the element with the index -1:
Types: Lists and
>>> lst = ["easy", "simple", "cheap", "free"] Python 3
Strings
>>> lst[-1]
List 'free' This is a tutorial in
Manipulations >>> Python3, but this
Shallow and chapter of our course
Deep Copy is available in a
Dictionaries version for Python
Sets and Frozen 2.x as well: in Python
Sets pop and append 2.x
An Extensive
Example Using s.append(x) Book a
Sets This method appends an element to the end of the list "s". Dedicated
input via the Course
>>> lst = [3, 5, 7]
keyboard >>> lst.append(42)
Conditional >>> lst The goal of this
[3, 5, 7, 42] website is to provide
Statements
>>> educational material,
Loops, while
allowing you to learn
Loop It's import to understand that append returns "None". This means that it usually doesn't make sense to reassign the return value: Python on your own.
For Loops Nevertheless, it is
Difference >>> lst = [3, 5, 7]
faster and more
>>> lst = lst.append(42)
between >>> print(lst) efficient to attend a
interators und None "real" Python course
Iterables >>> in a classroom, with
an experienced
Output with Print
s.pop(i) trainer. So why not
Formatted output
'pop' returns the ith element of a list s. The element will be removed from the list as well. attend one of the live
with string Python courses
modulo and the >>> cities = ["Hamburg", "Linz", "Salzburg", "Vienna"]
format method >>> cities.pop(0)
'Hamburg'
Functions
>>> cities
Recursion and ['Linz', 'Salzburg', 'Vienna']
Recursive >>> cities.pop(1)
Functions 'Salzburg'
>>> cities
Parameter ['Linz', 'Vienna']
Passing in >>>
Functions
Namespaces The method 'pop' raises an IndexError exception if the list is empty or the index is out of range.
Global and Local s.pop()
The method 'pop' can be called without an argument. In this case, the last element will be returned. So s.pop() is equivalent to s.pop(-1).
Variables
in Paris, London,
Decorators >>> cities = ["Amsterdam", "The Hague", "Strasbourg"] Berlin, Munich or
Memoization with >>> cities.pop() Lake Constance by
Decorators 'Strasbourg' Bernd Klein, the
>>> cities
Read and Write author of this
['Amsterdam', 'The Hague']
Files >>> tutorial?
Modular
Programming
and Modules Onsite Training
Packages in Courses
Python extend
Let us come to your
Regular
company or institute
Expressions We saw that it is easy to append an object to a list. But what about adding more than one element to a list? Maybe, you want to add all the elements of another list to your list. If you use append, the other list will
and train your
Regular be appended as a sublist, as we can see in the following example:
employees, as we've
Expressions, done it many times in
>>> lst = [42,98,77]
Advanced >>> lst2 = [8,69] Amsterdam (The
Lambda >>> lst.append(lst2) Netherlands), Berlin
Operator, Filter, >>> lst (Germany), Bern
Reduce and Map [42, 98, 77, [8, 69]] (Switzerland), Basel
>>> (Switzerland), Zurich
List
(Switzerland),
Comprehension What we wanted to accomplish is the following: Locarno
Iterators and
(Switzerland), Den
Generators [42, 98, 77, 8, 69]
Haag (The Hague),
Exception Hamburg (Germany),
To this purpose, Python provides the method 'extend'. It extends a list by appending all the elements of an iterable like a list, a tuple or a string to a list:
Handling Frankfurt (Germany),
Tests, DocTests, >>> lst = [42,98,77] Toronto (Canada),
UnitTests >>> lst2 = [8,69] Edmonton (Canada),
>>> lst.extend(lst2) Munich (Germany)
Object Oriented
>>> lst and many other
Programming [42, 98, 77, 8, 69]
cities. We do training
Class and >>>
courses in England,
Instance Switzerland,
Attributes As we have mentioned, the argument of extend doesn't have to be a list. It can be any iterable. This means that we can use tuples and strings as well:
Liechtenstein,
Properties vs. >>> lst = ["a", "b", "c"] Austria, Germany,
getters and >>> programming_language = "Python" France, Belgium, the
setters >>> lst.extend(programming_language) Netherlands,
>>> print(lst) Luxembourg, Poland,
Inheritance
['a', 'b', 'c', 'P', 'y', 't', 'h', 'o', 'n'] UK, Italy and other
Multiple
locations in Europe
Inheritance Now with a tuple:
and in Canada.
Magic Methods
>>> lst = ["Java", "C", "PHP"]
and Operator This way you will get
>>> t = ("C#", "Jython", "Python", "IronPython")
Overloading >>> lst.extend(t) a perfect training up
OOP, Inheritance >>> lst to your needs and it
Example ['Java', 'C', 'PHP', 'C#', 'Jython', 'Python', 'IronPython'] will be extremely cost
>>> efficient as well.
Slots
Classes and Contact us so we can
define and find the
Class Creation
best course
Road to
curriculum to meet
Metaclasses
Extending and Appending Lists with the '+'-Operator your needs, and
Metaclasses schedule course
Metaclass Use There is an alternative to 'append' and 'extend'. '+' can be used to combine lists. sessions to be held at
Case: Count your location.
Function Calls >>> level = ["beginner", "intermediate", "advanced"]
>>> other_words = ["novice", "expert"]
Abstract Classes
>>> level + other_words
['beginner', 'intermediate', 'advanced', 'novice', 'expert'] Skilled Python
>>> Programmers

Be careful. Never ever do the following: You can hire skilled


Python programmers
>>> L = [3, 4] or even a skilled
Lists >>> L = L + [42]
team of Python
>>> L
electoral list, to-do [3, 4, 42] developers to work
list, best-of list, >>> exclusively on your
inventory list, project. Contact us, if
brainstorming list, Even though we get the same result, it is not an alternative to 'append' and 'extend': you want more
check list, timeline information.
>>> L = [3, 4]
list, shopping list >>> L.append(42)
>>> L
Quote of the
These lists can be all [3, 4, 42] Day:
implemented in >>>
Python! >>> We can only see a
>>> L = [3, 4] short distance ahead,
Supported by: >>> L.extend([42])
but we can see
>>> L
[3, 4, 42] plenty there that
Training Courses in >>> needs to be done.
Python Alan Turing
The augmented assignment (+=) is an alternative:

>>> L = [3, 4]
>>> L += [42]
>>> L
[3, 4, 42]
Data Protection
We will compare in the following example the different approaches and calculate their run times. To understand the following program, you need to know that time.time() returns a float number, the time in seconds
Declaration
since the so-called ,,The Epoch''1. time.time() - start_time calculates the time in seconds consumed for the for loops:
Data Protection
import time Declaration

n= 100000

start_time = time.time()
l = []
for i in range(n):
l = l + [i * 2]
print(time.time() - start_time)

start_time = time.time()
l = []
for i in range(n):
l += [i * 2]
print(time.time() - start_time)

start_time = time.time()
l = []
for i in range(n):
l.append(i * 2)
print(time.time() - start_time)

This program returns shocking results:

26.3175041676
0.0305399894714
0.0207479000092

We can see that the "+" operator is about 1268 slower than the append method. The explanation is easy: If we use the append method, we will simply append a further element to the list in each loop pass. Now we
come to the first loop, in which we use l = l + [i * 2]. The list will be copied in every loop pass. The new element will be added to the copy of the list and result will be reassigned to the variable l. After this the old
list will have to be removed by Python, because it is not referenced anymore. We can also see that the version with the augmented assignment ("+="), the loop in the middle, is only slightly slower than the version
using "append".

Removing an element with remove

It is possible to remove with the method "remove" a certain value from a list without knowing the position.

s.remove(x)

This call will remove the first occurrence of x from the list s. If x is not contained in the list, a ValueError will be raised. We will call the remove method three times in the following example to remove the colour
"green". As the colour "green" occurrs only twice in the list, we get a ValueError at the third time:

>>> colours = ["red", "green", "blue", "green", "yellow"]


>>> colours.remove("green")
>>> colours
['red', 'blue', 'green', 'yellow']
>>> colours.remove("green")
>>> colours
['red', 'blue', 'yellow']
>>> colours.remove("green")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>>

Find the Position of an Element in a List

The method "index" can be used to find the position of an element within a list:

s.index(x[, i[, j]])

It returns the first index of the value x. A ValueError will be raised, if the value is not present. If the optional parameter i is given, the search will start at the index i. If j is also given, the search will stop at position
j.

>>> colours = ["red", "green", "blue", "green", "yellow"]


>>> colours.index("green")
1
>>> colours.index("green", 2)
3
>>> colours.index("green", 3,4)
3
>>> colours.index("black")
Traceback (most recent call last):
File "", line 1, in
ValueError: 'black' is not in list
>>>

insert

We have learned that we can put an element to the end of a list by using the method "append". To work efficiently with a list, we need also a way to add elements to arbitrary positions inside of a list. This can be
done with the method "insert":

s.insert(index, object)

An object "object" will be included in the list "s". "object" will be placed before the element s[index]. s[index] will be "object" and all the other elements will be moved one to the right.

>>> lst = ["German is spoken", "in Germany,", "Austria", "Switzerland"]


>>> lst.insert(3, "and")
>>> lst
['German is spoken', 'in Germany,', 'Austria', 'and', 'Switzerland']
>>>

The functionality of the method "append" can be simulated with insert in the following way:

>>> abc = ["a","b","c"]


>>> abc.insert(len(abc),"d")
>>> abc
['a', 'b', 'c', 'd']
>>>

Footnotes:

1 Epoch time (also known as Unix time or POSIX time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1
January 1970, not counting leap seconds.

Previous Chapter: Sequential Data Types: Lists and Strings


Next Chapter: Shallow and Deep Copy

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like