How do I add odd value values ββin python?
I need 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 need to add 5 to every odd position, the output should be
L = [1,8,5,12,9,16]
I am focused on where to start, I have to use indexing and a for loop, but everything I try doesn't work. That'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
source to share
You can use a list comprehension , one of the greatest features of python:
L = [1,3,5,7,9,11]
L2 = [L[i]+5 if i%2 else L[i] for i in range(0,len(L))]
or, as @matiasg suggested:
L2 = [L[i] + 5 * (i % 2) for i in range(len(L))]
source to share
You can link your list. Crossing assigns indices to your original list from another list of sources. This "other source list" can come from a simple list comprehension that is formed from another fragment.
>>> 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]
Description of the slicing syntax
Slicing is when you take a final sequence and index it with 1-2 colon characters to select a subsequence. A slice with 1 colon character has the format:
[start:stop]
A slice with two colons has the format:
[start:stop:step]
Arguments can be omitted and then 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 not specified, it defaults to the last valid sequence index + 1, or equivalently the sequence length. If step is omitted, it defaults to 1.
So when you make a slice of type seq[1::2]
, you say, get items seq
at indices starting at index 1 inclusive (specified by you), stopping at index len(seq)
exclusive (default value), and step by step 2 each time (specified by you).
Help understanding description
A list comprehension can be thought of as a concise, Pythonic way of doing display and filtering operations on an arbitrary number of potentially nested iterations over the iterations. If none of this makes sense to you, don't worry! You can find out all the data about the card and movies later. For now, just think about understanding the list [x+5 for x in L[1::2]]
as:
newlist = []
for x in L[1::2]:
newlist.append(x+5)
And then the newlist
list comprehension value will be set.
source to share
You are very close: if you want to go with your code, it is better to iterate over the list using for
in your case. Also, you first print the value and then increment it - so the printable value won't change.
The improved code looks like this:
def main():
L = [3,12,9,5,7,6,8]
for i in L:
if i%2 == 1:
print i + 5
elif i%2 == 0:
print i
source to share