element in list python code example

Example 1: how to make a python list

listName = [1,2,3,4]

Example 2: python find in list

# There is several possible ways if "finding" things in lists.
'Checking if something is inside'
3 in [1, 2, 3] # => True
'Filtering a collection'
matches = [x for x in lst if fulfills_some_condition(x)]
matches = filter(fulfills_some_condition, lst)
matches = (x for x in lst if x > 6)
'Finding the first occurrence'
next(x for x in lst if ...)
next((x for x in lst if ...), [default value])
'Finding the location of an item'
[1,2,3].index(2) # => 1
[1,2,3,2].index(2) # => 1
[1,2,3].index(4) # => ValueError
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]

Example 3: python lists

thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Example 4: how to call a specific element in a list python

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])

Example 5: a list inside a list python

board = []    
for i in range(6): # create a list with nested lists
    board.append([])
    for n in range(6):
        board[i].append("O") # fills nested lists with data

Example 6: list inside a list in python

# it appends a list into a list
list1 = [1,2,3,4,5]
list1.append([6,7])
# ouput = [1, 2, 3, 4, 5, [6, 7]]