Python List of Lists Incrementing
@tzaman gives the perfect solution, but you want your own code:
x = range (2)
y = []
for i in range (5):
y.append(x[:]) #You should append copy of x
x[0]+=1
print y
gives:
[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]]
How to create a list of lists where each sub-list 'increments' as follows: [1, 0, 0], [1, 1, 0], [1, 1, 1]
numValues = 12
result = [ [1] * i + [0] * (numValues - i) for i in range(1, numValues+1) ]
Increment of every element in list of lists with keeping the shape of the original list
You can do this with a nested list comprehension:
>>> a = [[1,2,3],[2,4],[3,5],[4,6,7]]
>>> [[y+i for y in x] for i in range(10) for x in a]
[[1, 2, 3], [2, 4], [3, 5], [4, 6, 7], [2, 3, 4], [3, 5], [4, 6], [5, 7, 8], [3, 4, 5], [4, 6], [5, 7], [6, 8, 9], [4, 5, 6], [5, 7], [6, 8], [7, 9, 10], [5, 6, 7], [6, 8], [7, 9], [8, 10, 11], [6, 7, 8], [7, 9], [8, 10], [9, 11, 12], [7, 8, 9], [8, 10], [9, 11], [10, 12, 13], [8, 9, 10], [9, 11], [10, 12], [11, 13, 14], [9, 10, 11], [10, 12], [11, 13], [12, 14, 15], [10, 11, 12], [11, 13], [12, 14], [13, 15, 16]]
The outermost iteration is for i in range(10)
, which takes you through the ten values of i
that will be added to the elements of a
. The next level for x in a
iterates over the elements of a
as x
. The inner list comprehension [y+i for y in x]
is what increments each x
by i
.
Python, creating a list of lists while creating incremented list names
Instead of:
var1
var2
var3
...
make var
a list, so you have:
var[0]
var[1]
var[2]
...
The entries in a list can be lists themselves. As a general rule, if you ever have a programming problem that seems to require the creation of a bunch of variables that all hold the same kind of thing, you probably want to create a single container (like a list or a dict) that holds all those values so that you can easily iterate over them (no matter how many there are) instead of having to type out a bunch of individual names and being limited to a certain fixed number of them.
Here's a very quick example in the REPL of how you could build a list of eight-element lists of two-character strings based on a single input string:
>>> string = "asldkfjalskdfjalskdjflaskdjflaskdjflaksdjfkjsldkfjsldakjfsdlkaaa"
>>> var = [[]]
>>> for i in range(0, len(string), 2):
... if len(var[-1]) == 8:
... var.append([])
... var[-1].append(string[i:i+2])
...
>>> var
[['as', 'ld', 'kf', 'ja', 'ls', 'kd', 'fj', 'al'], ['sk', 'dj', 'fl', 'as', 'kd', 'jf', 'la', 'sk'], ['dj', 'fl', 'ak', 'sd', 'jf', 'kj', 'sl', 'dk'], ['fj', 'sl', 'da', 'kj', 'fs', 'dl', 'ka', 'aa']]
>>> var[0]
['as', 'ld', 'kf', 'ja', 'ls', 'kd', 'fj', 'al']
>>> var[1]
['sk', 'dj', 'fl', 'as', 'kd', 'jf', 'la', 'sk']
>>> var[2]
['dj', 'fl', 'ak', 'sd', 'jf', 'kj', 'sl', 'dk']
>>> var[3]
['fj', 'sl', 'da', 'kj', 'fs', 'dl', 'ka', 'aa']
Here we're taking advantage of the range
function to help us iterate over the indices of the string in steps of 2, and we're using string slicing (string[i:i+2]
) to easily grab those two-character slices.
var[-1]
is always the last element of the list var
, which starts as a list containing a single empty list ([[]]
); as we iterate through the string, we're always appending those two characters onto the end of the last list.
We also always check to see if var[-1]
has reached eight elements yet; if so, that sublist is done, so we append
a new empty list to the end of var
so we can start a new one.
Increment all values in a list
You can use list-comprehension:
def incr(lst, i):
return [x+i for x in lst]
Find the first element in a list where all subsequent values increment by one
Here's an itertools
based one, useful if we have a very long list, so we don't have load it into memory. Here dropwhile
will drop values from the iterable while the condition holds, we only need to take the next
element in the resulting iterable. Note that next
has a default argument, which we can just set to None
to avoid having the StopIteration
error being raised:
from itertools import tee, dropwhile
def first_diff(it):
i, j = tee(reversed(it), 2)
next(j)
return next((dropwhile(lambda e: e==(next(j)+1), i)), None)
first_diff(my_list1)
# 15
first_diff(my_list2)
# 20
first_diff(my_list3)
# 18
Increase all of a lists values by an increment
Specific answer
With list comprehensions:
In [2]: list1 = [1,2,3,4,5,6]
In [3]: [x+170 for x in list1]
Out[3]: [171, 172, 173, 174, 175, 176]
With map
:
In [5]: map(lambda x: x+170, list1)
Out[5]: [171, 172, 173, 174, 175, 176]
Turns out that the list comprehension is twice as fast:
$ python -m timeit 'list1=[1,2,3,4,5,6]' '[x+170 for x in list1]'
1000000 loops, best of 3: 0.793 usec per loop
$ python -m timeit 'list1=[1,2,3,4,5,6]' 'map(lambda x: x+170, list1)'
1000000 loops, best of 3: 1.74 usec per loop
Some bench-marking
After @mgilson posted the comment about numpy, I wondered how it stacked up. I found that for lists shorter than 50 or so elements, list comprehensions are faster, but numpy is faster beyond that.
How to increment all values in a matrix (list of lists) by n?
You can write a simple function to iterate over your list to increment each element by n
as such:
def increment_by_n(lst, n):
for i in range(len(lst)):
for j in range(len(lst[i])):
lst[i][j] += n
return lst
With regards to explaining line4: lst[i][j] += n
, let's explore the following:
for i in range(len(lst)): # line 2
# the above means : for i in [0, 1, 2]
# because len(lst) = 3 and hence range(3) = [0, 1, 2]
# we use this to reference lst[i], i.e lst[0] = [8, 9], lst[1] = [5, 7]
# Note that lst[0][0] = 8, we will use this below!
for j in range(len(lst[i])): # line 3
# first, len(lst[0]) = len(lst[8, 9]) = 2
# range(2) = [0, 1]
# so the above means: for j in [0, 1]
lst[i][j] += n # Line 4
# We are here referencing the i in [0, 1, 2] and j in [0, 1] in order
# lst[0][0] = 8 and hence, 8 + 1 = 9
# lst[0][1] = 9 and hence, 9 + 1 = 10
# lst[1][0] = 5 and hence, 5 + 1 = 6, and so on...
Note that this will modify your initial list.
How can I increment only the first element of the first row of a Python list of lists?
If s is truly a list of lists (and not a list containing multiple references to the same list), what you did works, your issue must be elsewhere
>>> s = [[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]]
>>> s[0][0]
0
>>> s[0][0] = 1
>>> s
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Related Topics
How to Flatten a Hierarchical Index in Columns
How to Downgrade Tensorflow, Multiple Versions Possible
Ioerror: [Errno 32] Broken Pipe When Piping: 'Prog.Py | Othercmd'
How to Create a Common Function to Execute a Python Script in Jenkins
Best Way to Identify and Extract Dates from Text Python
Remove the Selected Elements from the Image in Opencv
How to Split a Huge Text File in Python
Exclude First Row When Importing Data from Excel into Python
Navigating Through Pagination With Selenium in Python
If-Condition With Multiple Actions in Robot Framework
How to Print Just the First Letters of Each Word
Valueerror: Invalid \Escape Unable to Load Json from File
Python Flask Threaded True Not Working
Webscraping Financial Data from Morningstar
Test a Function Called Twice in Python