4

My input is a list, say l

It can either contain 4 or 5 elements. I want to assign it to 5 variables , say a, b, c, d and e.

If the list has only 4 elements then the third variable (c) should be None.

If python had an increment (++) operator I could do something like this.

l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
    c = l[i++]
d = l[i++]
e = l[i++]

I can't seem to find an elegant way to do this apart from writing i+=1 before each assignment. Is there a simpler pythonic way to do this?

martineau
  • 119,623
  • 25
  • 170
  • 301
dCoder
  • 509
  • 3
  • 16

4 Answers4

10

You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate ++:

a, b, *c, d, e = l
c = c[0] if c else None

The *c target receives a list of all elements of l that weren't unpacked into the other targets. If this list is nonempty, then c is considered true when coerced to boolean, so c[0] if c else None takes c[0] if there is a c[0] and None otherwise.

user2357112
  • 260,549
  • 28
  • 431
  • 505
6

In the specific case of this question, list unpacking is the best solution.

For other users needing to emulate ++ for other purposes (typically the desire to increment without an explicit i += 1 statement), they can use itertools.count. This will return an iterator that will increment indefinitely each time it is passed to next().

import itertools

i = itertools.count(0)  # start counting at 0
print(next(i))  # 0
print(next(i))  # 1
# ...and so on...
SethMMorton
  • 45,752
  • 12
  • 65
  • 86
0

I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition.

l = [4 or 5 string inputs]

a = l[0]
b = l[1]

if len(l) > 4:
    c = l[2]
    d = l[3]
    e = l[4]
else:
    c = None
    d = l[2]
    e = l[3]
Simon Notley
  • 2,070
  • 3
  • 12
  • 18
0

There is no ++ operator in Python. A similar question to this was answered here Behaviour of increment and decrement operators in Python

MasterOfTheHouse
  • 1,164
  • 1
  • 14
  • 34