3
mylist=[]
mylist.append(7)
mylist.extend(range(9,12))

can such a thing be done in a single line in python3?

I feel it should be trivial, but for some reason I can't recall nor find how to do that.

o0'.
  • 11,739
  • 19
  • 60
  • 87

3 Answers3

8

You can use this one liner:

mylist = [7] + list(range(9,12))

It returns the desired list:

[7, 9, 10, 11]
o0'.
  • 11,739
  • 19
  • 60
  • 87
cfedermann
  • 3,286
  • 19
  • 24
  • I guess I'm missing something, since `for lid in [7] + range(9,len(row)):` gives me `TypeError: can only concatenate list (not "range") to list` – o0'. Apr 13 '12 at 10:33
  • This works in Python 2.7 -- maybe you are using another version? Check if the mylist=... assigment works for you. – cfedermann Apr 13 '12 at 10:37
  • 3
    `range` doesn't give a precalculated list anymore in Py3, but you can still explicitly make one out of it if you want that: `mylist = [7] + list(range(9, 12))` – lvc Apr 13 '12 at 10:41
2

You can add whatever you want to the list constructor. For example:

mylist = [7]

Or:

mylist = list(range(9,12))

or, to chain the two together:

mylist = [7] + list(range(9,12))

For more complex constructions, list comprehensions are the way to go. For example:

mylist = [ (irow,icol) for irow in range(1,10) for irow in range(1,10) if i > j ]

More information on list comprehensions is available at: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

(Edited to reflect the change in the question).

Pascal Bugnion
  • 4,878
  • 1
  • 24
  • 29
1

If you are using Python 2.* as others have said

for lid in [7] + range(9,len(row)):

will work

if working with Python 3.*, as range now returns an iterator you need to explicitly convert to list

Option 1:

for lid in [7] + list(range(9,len(row))):

Option 2:

for lid in itertools.chain([7],range(9,len(row))):
Abhijit
  • 62,056
  • 18
  • 131
  • 204