## Posts Tagged ‘lists’

## Python: Using a List of Lists in a Function

def flatten(lists):

results = []

for lst in lists:

results.append(numbers)

return results

print flatten(n)

## Python: How to Merge/Join 2 Lists

m = [1, 2, 3]

n = [4, 5, 6]

def join_lists(x, y):

return x+y

print join_lists(m, n)

# You want this to print [1, 2, 3, 4, 5, 6]

## Python: use ”.join(list) to concatenate a list of strings

# Add your function here

def join_strings(words):

result = “”

for i in words:

result = ”.join(words)

print result

return result

## Python: List appends and other list functions

`list.``append`(*x*)- Add an item to the end of the list; equivalent to
`a[len(a):] = [x]`.

`list.``extend`(*L*)- Extend the list by appending all the items in the given list; equivalent to
`a[len(a):] = L`.

`list.``insert`(*i*,*x*)- Insert an item at a given position. The first argument is the index of the element before which to insert, so
`a.insert(0, x)`inserts at the front of the list, and`a.insert(len(a), x)`is equivalent to`a.append(x)`.

`list.``remove`(*x*)- Remove the first item from the list whose value is
*x*. It is an error if there is no such item.

`list.``pop`([*i*])- Remove the item at the given position in the list, and return it. If no index is specified,
`a.pop()`removes and returns the last item in the list. (The square brackets around the*i*in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

`list.``index`(*x*)- Return the index in the list of the first item whose value is
*x*. It is an error if there is no such item.

`list.``count`(*x*)- Return the number of times
*x*appears in the list.

`list.``sort`()- Sort the items of the list, in place.

`list.``reverse`()- Reverse the elements of the list, in place.

An example that uses most of the list methods:

>>> a = [66.25, 333, 333, 1, 1234.5]>>> print a.count(333), a.count(66.25), a.count('x')2 1 0>>> a.insert(2, -1)>>> a.append(333)>>> a[66.25, 333, -1, 333, 1, 1234.5, 333]>>> a.index(333)1>>> a.remove(333)>>> a[66.25, -1, 333, 1, 1234.5, 333]>>> a.reverse()>>> a[333, 1234.5, 1, 333, -1, 66.25]>>> a.sort()>>> a[-1, 1, 66.25, 333, 333, 1234.5]

## Python: Add each element of a list

def total(numbers):

result = 0

for i in range(len(numbers)):

for i in numbers:

result = sum(numbers)

print result

return result

## Python: Counting up the elements in a list of arbitrary size in a function

Now that we’ve learned about`range`

, we have two ways of iterating through a list.

**Method 1** – `for item in list`

:

```
for item in list:
print item
```

**Method 2** – iterate through indexes:

```
for i in range(len(list)):
print list[i]
```

Method 1 is a little easier, but can cause problems when trying to modify the list. Method 2 is **much** safer. Since we aren’t modifying the list, feel free to use either one on this lesson!