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

5.lists: 5.1. Accessing Values in Lists Ex

Python has a powerful built-in list data type that can be accessed and manipulated in various ways. Lists use square brackets and support accessing elements by index, slicing subsets, and determining the length of the list. Lists can be iterated over using for loops and checked for elements using the in operator. The list data type has various useful methods like append(), insert(), remove(), pop(), and more to dynamically add, remove, or manipulate elements. Lists are mutable and support common operations like sorting.

Uploaded by

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

5.lists: 5.1. Accessing Values in Lists Ex

Python has a powerful built-in list data type that can be accessed and manipulated in various ways. Lists use square brackets and support accessing elements by index, slicing subsets, and determining the length of the list. Lists can be iterated over using for loops and checked for elements using the in operator. The list data type has various useful methods like append(), insert(), remove(), pop(), and more to dynamically add, remove, or manipulate elements. Lists are mutable and support common operations like sorting.

Uploaded by

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

5.

Lists

Python has a great built-in list type named "list". List literals are written within square
brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to
access data. Important thing about a list is that items in a list need not be of the same

Creating a list is as simple as putting different comma-separated values between square


brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

5.1. Accessing Values in Lists

Ex:

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


print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables
point to the one list in memory.

b = colors ## Does not copy the list

5.2 The list() Constructor


It is also possible to use the list() constructor to make a list. To add an item to the list
use append() object method. To remove a specific item use the remove() object method.
The len() function returns the length of the list.

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


print(thislist)
5.3.1. List Slices

list = ['a', 'b', 'c', 'd']


print list[1:-1] ## ['b', 'c']
list[0:2] = 'z' ## replace ['a', 'b'] with ['z']
print list ## ['z', 'c', 'd']

5.3.2. FOR and IN

Ex1:

squares = [1, 4, 9, 16]


sum = 0
for num in squares:
sum += num
print sum ## 30

Ex2:

list = ['larry', 'curly', 'moe']


if 'curly' in list:
print 'yay'

5.3.3. Range

Ex:

## print the numbers from 0 through 99


for i in range(100):
print ( i )

5.3.4. While Loop

Ex:

## Access every 3rd element in a list


i=0
while i < len(a):
print a[i]
i=i+3
5.4.Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and you can add to elements in a list with the append() method.
For example −

#!/usr/bin/python

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

Result:
Value available at index 2 :
1997
New value available at index 2 :
2001

5.5. Delete List Elements


#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1

Result:

['physics', 'chemistry', 1997, 2000]


After deleting value at index 2 :
['physics', 'chemistry', 2000]
5.6. List Methods

Common Methods with example:

list = ['larry', 'curly', 'moe']


list.append('shemp') ## append elem at end
list.insert(0, 'xxx') ## insert elem at index 0
list.extend(['yyy', 'zzz']) ## add list of elems at end
print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly') ## 2

list.remove('curly') ## search and remove that element


list.pop(1) ## removes and returns 'larry'
print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Python Lists
Python has a great built-in list type named "list". List literals are written within square
brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to
access data, with the first element at index 0. (See the official python.org list docs.)

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


print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3

Assignment with an = on lists does not make a copy. Instead, assignment makes the two
variables point to the one list in memory.

b = colors ## Does not copy the list

The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1,
2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).
FOR and IN

Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see
is with lists. The *for* construct -- for var in list -- is an easy way to look at each element in a
list (or other collection). Do not add or remove from the list during iteration.

squares = [1, 4, 9, 16]


sum = 0
for num in squares:
sum += num
print sum ## 30

If you know what sort of thing is in the list, use a variable name in the loop that captures
that information such as "num", or "name", or "url". Since python code does not have other
syntax to remind you of types, your variable names are a key way for you to keep straight
what is going on.

The *in* construct on its own is an easy way to test if an element appears in a list (or other
collection) -- valuein collection -- tests if the value is in the collection, returning True/False.

list = ['larry', 'curly', 'moe']


if 'curly' in list:
print 'yay'

The for/in constructs are very commonly used in Python code and work on data types other
than list, so you should just memorize their syntax. You may have habits from other
languages where you start manually iterating over a collection, where in Python you should
just use for/in.

You can also use for/in to work on a string. The string acts like a list of its chars, so for ch in s:
print chprints all the chars in a string.

Range
The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1 --
up to but not including the last number. The combination of the for-loop and the range()
function allow you to build a traditional numeric for loop:

## print the numbers from 0 through 99


for i in range(100):
print i

There is a variant xrange() which avoids the cost of building the whole list for performance
sensitive cases (in Python 3000, range() will have the good performance behavior and you
can forget about xrange()).
While Loop
Python also has the standard while-loop, and the *break* and *continue* statements work
as in C++ and Java, altering the course of the innermost loop. The above for/in loops solves
the common case of iterating over every element in a list, but the while loop gives you total
control over the index numbers. Here's a while loop which accesses every 3rd element in a
list:

## Access every 3rd element in a list


i=0
while i < len(a):
print a[i]
i=i+3

List Methods
Here are some other common list methods with example.

Notice that these are *methods* on a list object, while len() is a function that takes the list
(or string or whatever) as an argument.

list = ['larry', 'curly', 'moe']


list.append('shemp') ## append elem at end
list.insert(0, 'xxx') ## insert elem at index 0
list.extend(['yyy', 'zzz']) ## add list of elems at end
print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly') ## 2

list.remove('curly') ## search and remove that element


list.pop(1) ## removes and returns 'larry'
print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Common error: note that the above methods do not *return* the modified list, they just
modify the original list.

list = [1, 2, 3]
print list.append(4) ## NO, does not work, append() returns None
## Correct pattern:
list.append(4)
print list ## [1, 2, 3, 4]

While a function is what you can apply on a construct and get a result, a method is what you can
do to it and change it. To call a method on a construct, you use the dot-operator(.). Python
supports some built-in methods to alter a list.
a. append()
It adds an item to the end of the list.
>>> a
[2, 1, 3]

1. >>> a.append(4)
2. >>> a
[2, 1, 3, 4]

b. insert()
It inserts an item at a specified position.

1. >>> a.insert(3,5)
2. >>> a
[2, 1, 3, 5, 4]
This inserted the element 5 at index 3.

c. remove()
It removes the first instance of an item from the list.

1. >>> a=[2,1,3,5,2,4]
2. >>> a.remove(2)
3. >>> a
[1, 3, 5, 2, 4]
Notice how there were two 2s, but it removed only the first one.

d. pop()
It removes the element at the specified index, and prints it to the screen.
>>> a.pop(3)
2
>>> a
[1, 3, 5, 4]

e. clear()
It empties the list.

1. >>> a.clear()
2. >>> a
[]
It now has a False value.
>>> bool(a)
False

f. index()
It returns the first matching index of the item specified.

1. >>> a=[1,3,5,3,4]
2. >>> a.index(3)
1

g. count()
It returns the count of the item specified.
>>> a.count(3)
2

h. sort()
It sorts the list in an ascending order.

1. >>> a.sort()
2. >>> a
[1, 3, 3, 4, 5]

i. reverse()
It reverses the order of elements in the list.

1. >>> a.reverse()
2. >>> a
[5, 4, 3, 3, 1]
This was all about the Python lists

You might also like