0

I have a list of 3 lists each containing a random integer between 1 and 9:

lists= [[1,3,5],[2,4,6],[7,8,9]]

I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (assuming it is not the end of the list) is bigger or smaller.

for x in lists:
    for i in x:
        if i= user_choice-1:

Here I am stuck.

Lets say the user_choice is 3. I want the program to find the number 3-1=2 in the nested lists and then compare the number following 2 (in this case 4) to the user_choice.

  • So for each list in your list of list, you want x[user_choice+1] ? – Checkmate Aug 02 '16 at 21:22
  • 1
    Possible duplicate of [Access item in a list of lists](http://stackoverflow.com/questions/18449360/access-item-in-a-list-of-lists) – Keozon Aug 02 '16 at 21:23
  • 2
    `if i = user_choice - 1:` is an invalid syntax. `=`is for assignment, if you want to check for equality you need to write `if i == user_choice - 1: – Ted Klein Bergman Aug 02 '16 at 21:23
  • Indexing nested index should be `mainList[main_index][sub_index]` – RandomEli Aug 02 '16 at 21:25
  • 1
    It might clarify the question if you gave an example if what `user_choice` is or could be and what you would expect the return value to be. It is not clear what you are intending the code to do. – johnchase Aug 02 '16 at 21:25

4 Answers4

2

if your list is

lists= [[1,3,5],[2,4,6],[7,8,9]]

to access the "1" you would type: lists[0][0] to access the "8" you would type: lists[2][1]

*remember lists start their index at 0!!! :)

fugu
  • 6,417
  • 5
  • 40
  • 75
Connor Meeks
  • 501
  • 1
  • 6
  • 19
1

I am a little confused by what you are trying to achieve but you can get the index along with the element in a for loop by using:

for index, value in enumerate(my_list):
    # Do stuff here

Or you can find the index of any element in a list with:

index = my_list.index(value)

Don't forget to change you = to a == in your if statement, by the way.

Ulf Gjerdingen
  • 1,414
  • 3
  • 16
  • 20
Dr K
  • 416
  • 2
  • 5
  • Ultimately what I want to do is swap items from one list to another, but since the lists are nested I need to know how to properly write the index of the elements I want to swap. –  Aug 02 '16 at 21:49
0
lists= [[1,3,5],[2,4,6],[7,8,9]]

for x in lists:
    index = 0
    for i in x:
        index += 1
        if i == user_choice - 1:
            print(x[index])
        else:
            (...)
fugu
  • 6,417
  • 5
  • 40
  • 75
0

If I understand correctly, you want:

for x in lists:
    for i in range(len(x)):
        if x[i] == user_choice-1 and i < len(x)-1:
            if x[i+1] > x[i]:
                #Next value is bigger...
            else:
                #Next value is smaller...
Checkmate
  • 1,074
  • 9
  • 16