use a loop to create lists

M

martaamunar

Hi!

I would like to create a list containing lists. I need each list to have a differente name and i would like to use a loop to name the list. But as the name, is a string, i cannot asign it to a value... how can I do that??


global_list=[]
for i in range (20):
("list_"+i)=[] #These would be the name of the list...
global_list.append("list_"+i)

Thank you!!!!!
 
C

Chris Angelico

Hi!

I would like to create a list containing lists. I need each list to have a differente name and i would like to use a loop to name the list. But as the name, is a string, i cannot asign it to a value... how can I do that??


global_list=[]
for i in range (20):
("list_"+i)=[] #These would be the name of the list...
global_list.append("list_"+i)

They don't need unique names. Just use the same name inside the loop:

global_list=[]
for i in range(20):
current_list=[] # Presumably you do something with it here
global_list.append(current_list)

That'll work fine, and you can reference the lists by their positions
in global_list.

ChrisA
 
D

Dave Angel

Hi!

I would like to create a list containing lists. I need each list to have a differente name and i would like to use a loop to name the list. But as the name, is a string, i cannot asign it to a value... how can I do that??


global_list=[]
for i in range (20):
("list_"+i)=[] #These would be the name of the list...
global_list.append("list_"+i)

Thank you!!!!!

The fact that the content of the outer list also happens to be lists is
irrelevant to your question. I believe the real question here is how to
create an arbitrary bunch of new names, and bind them to elements of he
list.

In general, you can't. But more importantly, in general you don't want
to. If you come up with a convoluted way to fake it, you'll have to use
the same convoluted way to access those names, so there's no point. As
Chris says, just reference them by index.

On the other hand, if the outer list happens to have exactly 7 elements,
and you know that ahead of time, then it may well make sense to assign
names to them. Not list_0 through list_6, but name, addr1, ec.

global_list = []
for i in range(7):
global_list.append[]

first_name, mid_name, last_name, addr1, addr2, city, town = global_list

Incidentally, that's approximately what a collections.namedtuple is all
about, giving names to items that are otherwise considered elements of a
tuple.
 
T

Thomas Goebel

* On 10/04/2013 10:40 said:
Hi!

I would like to create a list containing lists. I need each list to
have a differente name and i would like to use a loop to name the
list.
[...]
global_list=[]
for i in range (20):
("list_"+i)=[] #These would be the name of the list...
global_list.append("list_"+i)

You can use a dictionary instead of a list of lists:

global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}
global_list_1 = global_list['list_0']
 
R

rusi

Hi!

I would like to create a list containing lists. I need each list to have a differente name and i would like to use a loop to name the list. But as the name, is a string, i cannot asign it to a value... how can I do that??

global_list=[]
for i in range (20):
  ("list_"+i)=[]   #These would be the name of the list...
  global_list.append("list_"+i)

Thank you!!!!!


If as Chris points out you dont actually need names, a list should
suffice (with indexing serving as 'naming')
If however there are a fixed (at program-writing time) small set of
names, you can do as Dave suggests and use unpacking assignment. [Some
people like to use objects for this]
If however you need an arbitrary set of names, unknown at programming
time, a dictionary is typically what is appropriate:

For dictionary d
- get the value of name n with d[n]
- set (bind) name n to value v in dict d with d[n] = v

Which of these options you should follow is not clear from your
question; you need to tell us a bit more about what you are trying to
do.
 
F

Franz Kelnreiter

---------- Forwarded message ----------
From: Franz Kelnreiter <[email protected]>
Date: Thu, Apr 11, 2013 at 2:09 PM
Subject: Re: use a loop to create lists
To: (e-mail address removed)


On Thu, Apr 11, 2013 at 1:46 PM, Thomas Goebel <
global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}
global_list_1 = global_list['list_0'] --

Sorry Thomas, but you had a typo or in any case a wrong syntax
concept in your last posting. If you'd like to use list
comprehension it should be written as:

mydict = {'_'.join(['list', str(i)]):[x for x in range(20)]}

Hi Franz,

the difference between your and my code is that

global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}

creates a dict 'global_list' which has 20 keys named from 'list_0' to
'list_19'. The value for all keys is an empty list. If you want to
create i.e. 20 keys which value is a list with 20 ints you have to use

global_list = ({'_'.join(['list', str(i)]):[a for a in range(20)] for
i in range(20)})

Your code creates a dict with one key 'list_19' which value is a list
with 20 ints if you replace str(i) with str(a).

Regards, Tom

Tom,
Thanks for your explanation, I think I know what you want to do and I would
very much like to understand your code in detail - maybe I am too stupid -
but when I execute the value part of your code construct:

[a for a in range(20)] for i in range(20)

I get a syntax error, as I exepected (Python 2.6.4 (r264:75708, Oct 26
2009, 08:23:19)).

So how can you get me on the right direction to make your code running on
my machine?

Thank you, Franz
 
T

Thomas Goebel

the difference between your and my code is that

global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}

creates a dict 'global_list' which has 20 keys named from 'list_0' to
'list_19'. The value for all keys is an empty list. If you want to
create i.e. 20 keys which value is a list with 20 ints you have to use

global_list = ({'_'.join(['list', str(i)]):[a for a in range(20)] for
i in range(20)})

Thanks for your explanation, I think I know what you want to do and I would
very much like to understand your code in detail - maybe I am too stupid -
but when I execute the value part of your code construct:

This code
[a for a in range(20)] for i in range(20)

won't run because you you didn't define 'i'!

[a for a in range(3)]

will return a list
[0, 1, 2]


To get a dict with n keys we can use a for-loop, too:

d = {}
for n in range(3):
# Create keys 'list_0' to 'list_n'
d['list_' + str(n)] = []

So we finally get:
d.keys()
['list_2', 'list_1', 'list_0']

d.values()
[[], [], []]


Now we create a dict with n keys and for every key n we set the value
to a list of m ints:

e = {}
for n in range(3):
# Create keys 'list_0' to 'list_n'
e['list_' + str(n)] = []
for m in range(3):
# Create a list [0, 1, 2] for every key of e
e['list_' + str(n)].append(m)

The results is as follows:
e.keys()
['list_2', 'list_1', 'list_0']

e.values()
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Which is the same as:
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

I double checked the code and everything is working fine for me. Maybe
you forgot some braces?

P.S: I'm running on python 2.7.4:
'2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)]'
 
C

Chris Angelico

[a for a in range(3)]

will return a list
[0, 1, 2]

Simplification possible: That's the same as:

list(range(3))
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

Meaning that this can be simplified too:

f = {'list_' + str(n):list(range(3)) for n in range(3)}

ChrisA
 
T

Thomas Goebel

global_list = {'_'.join(['list', str(i)]):[] for i in range(20)}

Thanks for your explanation, I think I know what you want to do and I would
very much like to understand your code in detail - maybe I am too stupid -
but when I execute the value part of your code construct:

[a for a in range(20)] for i in range(20)

I get a syntax error, as I exepected (Python 2.6.4 (r264:75708, Oct 26
2009, 08:23:19)).

Sorry Franz,

as you are using python 2.6 you have to use

d1 = dict(('list_' + str(i), []) for i in range(3))
d2 = dict(('list_' + str(i), [m for m in range(3)]) for i in range(3))

like stated here:
http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension
 
F

Franz Kelnreiter

On Thu, Apr 11, 2013 at 2:57 PM, Thomas Goebel <
...
Which is the same as:
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

Thomas, thank you for your patience and your long explanation! Now I
understand better this shorthand expression of one single 'pythonic' ;)
line.
But didnt you miss square brackets:

f = {'list_' + str(n):[[m for m in range(3)] for n in range(3)]}

??
Otherwise the code wont work for me...
 
T

Thomas Goebel

On Thu, Apr 11, 2013 at 2:57 PM, Thomas Goebel <
...
Which is the same as:
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}
[...]
But didnt you miss square brackets:

f = {'list_' + str(n):[[m for m in range(3)] for n in range(3)]}

If i try your code i get a dict with key 'list_2' which value is a
list of three lists.

Maybe this occurs because we're using different python versions?! I
never used python<2.7!

Have you tried this one

d2 = dict(('list_' + str(i), list(range(3))) for i in range(3))

with Chris' simplification:

[a for a in range(3)]

will return a list
[0, 1, 2]

Simplification possible: That's the same as:

list(range(3))
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

Meaning that this can be simplified too:

f = {'list_' + str(n):list(range(3)) for n in range(3)}
 
F

Franz Kelnreiter

On Thu, Apr 11, 2013 at 3:43 PM, Thomas Goebel <
...
I get a syntax error, as I exepected (Python 2.6.4 (r264:75708, Oct 26
2009, 08:23:19)).

Sorry Franz,

as you are using python 2.6 you have to use

d1 = dict(('list_' + str(i), []) for i in range(3))
d2 = dict(('list_' + str(i), [m for m in range(3)]) for i in range(3))

like stated here:

http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension

Thank you, Thomas, for your last posting and your help, that makes
everything clear for me now!

All best, Franz
 
D

Dennis Lee Bieber

On Thu, Apr 11, 2013 at 2:57 PM, Thomas Goebel <
...
Which is the same as:
f = {'list_' + str(n):[m for m in range(3)] for n in range(3)}

Thomas, thank you for your patience and your long explanation! Now I
understand better this shorthand expression of one single 'pythonic' ;)
line.
But didnt you miss square brackets:

f = {'list_' + str(n):[[m for m in range(3)] for n in range(3)]}
Without the second set of square brackets, the result is a generator
expression/comprehension -- which came in a few versions after list
comprehensions did.

However, your position in locking the "n" inside the right hand, but
you need "n" on the left too...

Try moving the first [ to the beginning -- {["list....

(NO PROMISES -- I DIDN'T TEST}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top