By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,820 Members | 1,081 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,820 IT Pros & Developers. It's quick & easy.

Filling a list of lists...

P: 6
Here's my problem.
I need a matrix (a list of lists) of undefined size (maybe I should define it as an empty list?). The matrix will have a size of nxm but n and m will be introduced by the user.
Now, the user will also introduce the values for the matrix as a string, for example: list[0]="Hello" but I need to store that string as a list of 5 elements list[0]=[H, e, l, l, o]
Is there a not so complicated way to do that?

So far what I'm thinking is to define an empty list list=[] and then to ask for the number of lines the matrix will have, then to change the size of list according to the value introduced (no idea on how to do that). Once the list has the desired size, I'd ask for each of the strings and convert it to list using list(string) (I know there's such a function, but not sure if it works on lists inside a list)...
well, that's my idea. Python is the very first programming language I try to learn and don't know how to write it properly, so forgive me if this is a super easy thing and I'm drawning in my own ignorance.

Thanks for any tips and sorry for the long post.
Mar 12 '12 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 2.5K+
P: 2,851
See if this helps:
Expand|Select|Wrap|Line Numbers
  1. >>> cols = 6
  2. >>> rows = 4
  3. >>> m = [[None for i in range(cols)] for j in range(rows)]
  4. >>> m[0]
  5. [None, None, None, None, None, None]
  6. >>> word = "Hello"
  7. >>> word[:6]
  8. 'Hello'
  9. >>> for i, letter in enumerate(word[:cols]):
  10. ...     m[0][i] = letter
  11. ...     
  12. >>> m[0]
  13. ['H', 'e', 'l', 'l', 'o', None]
  14. >>> 
Mar 12 '12 #2

P: 6

Thanks for your reply. I tried the code and it worked perfectly. I made some minor modifications so it asked the user for the size of the matrix:
Expand|Select|Wrap|Line Numbers
  1. cols=input("How many columns will be in the matrix?: ")
  2. rows=input("How many rows will be in the matrix?: ")
I also implemented a While function so it asked the user to write as many strings as rows, each one as long as the number of columns:

Expand|Select|Wrap|Line Numbers
  1. while k<rows:
  2.     String=raw_input("Write a string: ")
  3.     for i, letter in enumerate(Seq[:cols]):
  4.         m[k][i]=letter
  5.     k=k+1
Thanks again, the code you provided was extremely useful.
Mar 12 '12 #3

Expert Mod 2.5K+
P: 2,851
You're welcome. :)

Sometimes a code snippet is all that it takes to point someone in the right direction.
Mar 13 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.