4 Replies - 363 Views - Last Post: 10 January 2013 - 11:49 PM Rate Topic: -----

#1 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,682
  • Joined: 13-March 10

Question regarding lists

Posted 09 January 2013 - 08:16 AM

Can anyone tell me what is happening behind the scenes when these 2 are executed?:

listOne = [0 for i in range(100)]

listTwo = [0] * 100



I believe (correct me if i am wrong) in the first example it just loops 100 times and calls append(0) on the list.
No idea, how second one is executed.
Is This A Good Question/Topic? 0
  • +

Replies To: Question regarding lists

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3239
  • View blog
  • Posts: 10,869
  • Joined: 12-December 12

Re: Question regarding lists

Posted 09 January 2013 - 08:36 AM

They both have the same result: creating a list of 0 to 99 elements each with the value 0.

listOne = [0 for i in range(100)]
print(listOne)
print(len(listOne))
listTwo = [0] * 100
print(listTwo)
print(len(listTwo))


The second version just repeats the value. The first version is a list comprehension, which can do a lot more!

listThree = [i * 2 for i in range(100)]
print(listThree)

This post has been edited by andrewsw: 09 January 2013 - 08:37 AM

Was This Post Helpful? 0
  • +
  • -

#3 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,682
  • Joined: 13-March 10

Re: Question regarding lists

Posted 09 January 2013 - 09:07 AM

I know what they do. This does not answer my question.
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3239
  • View blog
  • Posts: 10,869
  • Joined: 12-December 12

Re: Question regarding lists

Posted 09 January 2013 - 09:19 AM

View Postdarek9576, on 09 January 2013 - 09:07 AM, said:

I know what they do. This does not answer my question.


listOne = [0 for i in range(100)]

range(100) creates a range of values 0,..,99
for i in refers to each of these values as i (while looping through them)
0 is an expression that refers to each value (i) but, for this example, doesn't actually use the value of i
the square brackets create a list.

This post has been edited by andrewsw: 09 January 2013 - 09:20 AM

Was This Post Helpful? 0
  • +
  • -

#5 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 199
  • Joined: 28-August 12

Re: Question regarding lists

Posted 10 January 2013 - 11:49 PM

I think he means that he understands that Python is an [binterpreted[/b] language, namely a language that is written in C++. That and he wants to know the C++ code that this would be converted to (I could be wrong on both of these...)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1