I have to process the list to add an amount to every odd position. For example, if I start with
def main():
L = [1,3,5,7,9,11]
and have to add 5 to each odd position, the output should be
L = [1,8,5,12,9,16]
I'm stumped as to where to begin, I am supposed to use indexing and a for loop but everything I try is not working. Here's what I have so far
def main():
L = [3,12,9,5,7,6,8]
i=0
while i < len(L):
if i%2 == 1:
print L[i]
i = i+5
elif i%2 == 0:
print L
You can splice your list. Splicing is making assignments to indexes of your original list from another source list. This "other source list" can come from a simple list comprehension that is formed from another slice.
>>> L = [1,3,5,7,9,11]
>>> L[1::2] = [x+5 for x in L[1::2]]
>>> L
[1, 8, 5, 12, 9, 16]
Slicing syntax explanation
Slicing is when you take a finite sequence, and index it with 1-2 colon characters, with the goal of selecting a subsequence. A slice with 1 colon character has the format:
[start:stop]
A slice with 2 colon characters has the format:
[start:stop:step]
Arguments can be omitted and then they will be set to their default values. If start is omitted, it defaults to the first index of the sequence, or 0, since Python sequences are 0-indexed. If stop is omitted it defaults to the last valid index of the sequence + 1, or equivalently, the length of the sequence. If step is omitted, it defaults to 1.
So when you do a slice like seq[1::2], what you're saying is, get the elements of seq with indexes starting from index 1 inclusive (specified by you), stopping at index len(seq) exclusive (default value), and stepping by 2 every time (specified by you).
List comprehension explanation
A list comprehension can be thought of as a concise, Pythonic way to do map and filter operations on an arbitrary number of potentially nested iterations over iterables. If none of that makes sense to you, don't worry! You can learn all the map and filter stuff later. For now, just think of the list comprehension [x+5 for x in L[1::2]] as:
newlist = []
for x in L[1::2]:
newlist.append(x+5)
And then newlist would be set to the value of the list comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With