jamesfacts
jamesfacts

Reputation: 391

In a Python List - How to retrieve a variable stored in a known position? Python 2.7

I'm a Python beginner stuck on a simple issue. I might not be able to describe my issue clearly, but searching around hasn't been fruitful.

I have two nested lists in Python:

ny = []
bos = []
dc = []
mia = []
chi = []

ny = [bos, 'Boston', dc, 'Washington D.C.', chi, 'Chicago']
dc = [mia, 'Miami', chi, 'Chicago', ny, 'New York']

I wrote a function that prints every other item in a list, ie, just the human-readable values in these particular lists.

When I call the function like this:

print_stations(dc)

...it works normally:

1 .  Miami
2 .  Chicago
3 .  New York

But when I call it like this:

print_stations(ny[2])

...I get nothing.

Why isn't ny[2] == dc ? I'm sure I'm missing something very simple, but my Google skills seem to have failed me.

Upvotes: 0

Views: 104

Answers (4)

James
James

Reputation: 63

is you know the location, call the list and placed [Number here] within the brackets. list = ['Yellow', 'Red', 'blue']

If you want to get the 2nd on in the list, this is number 1 in the list as python counts from 0.

print(list[1])

result:

>>'Red'

Upvotes: 0

Jayant Arora
Jayant Arora

Reputation: 43

The error here is that you are assigning "dc" a value after "ny" is defined.

You will get an empty list when you will try print_station(ny[2])`

>>>print_station(ny[2])
>>>[]

but if you write the code like this:

ny = []
bos = []
dc = []
mia = []
chi = []

dc = [mia, 'Miami', chi, 'Chicago', ny, 'New York']
ny = [bos, 'Boston', dc, 'Washington D.C.', chi, 'Chicago']

print_station(ny[2])
print_station()
print_station()
print_station(dc)

you will get the following output:

>>>[[], 'Miami', [], 'Chicago', [], 'New York']


   [[], 'Miami', [], 'Chicago', [], 'New York']

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123240

You didn't store the name dc in the ny list. You stored a reference to the same list object.

You then rebound the name dc to point to a new list. The other reference still in the list didn't change with that.

Rather than create a new list for dc, alter it in-place. Add new entries to the existing list:

dc.extend([mia, 'Miami', chi, 'Chicago', ny, 'New York'])

or replace all elements in the list (which could be 0) with new contents:

dc[:] = [mia, 'Miami', chi, 'Chicago', ny, 'New York']

Upvotes: 2

khelwood
khelwood

Reputation: 59146

You have this:

dc = []

And then this:

ny = [bos, 'Boston', dc, 'Washington D.C.', chi, 'Chicago']

So you have put an empty list (dc) into your ny list. After that you reassign dc to something else, but the list at ny[2] is still the empty list you originally put in there.

Try assigning dc before you put it into ny, or try modifying dc instead of reassigning it.

Upvotes: 1

Related Questions