python how to create a list code example

Example 1: how to make a python list

listName = [1,2,3,4]

Example 2: creating a list in python

myList = [value,value,value] #note that you can use any amount of value
#you don not have to use value

Example 3: how to create a list in python

# Create a list
new_list = []

# Add items to the list
item1 = "string1"
item2 = "string2"

new_list.append(item1)
new_list.append(item2)

# Access list items
print(new_list[0])  
print(new_list[1])

Example 4: python list

#Creating lists
my_list = ['foo', 4, 5, 'bar', 0.4]
my_nested_list = ['foobar', ['baz', 'qux'], [0]]

#Accessing list values
my_list[2] # 5
my_list[-1] # 0.4
my_list[:2] # ['foo', 4, 5]
my_nested_list[2] # ['baz', 'quz']
my_nested_list[-1] # [0]
my_nested_list[1][1] # 'qux'

#Modifying lists
my_list.append(x) # append x to end of list
my_list.extend(iterable) # append all elements of iterable to list
my_list.insert(i, x) # insert x at index i
my_list.remove(x) # remove first occurance of x from list
my_list.pop([i]) # pop element at index i (defaults to end of list)
my_list.clear() # delete all elements from the list
my_list.index(x[, start[, end]]) # return index of element x
my_list.count(x) # return number of occurances of x in list
my_list.reverse() # reverse elements of list in-place (no return)
my_list.sort(key=None, reverse=False) # sort list in-place
my_list.copy() # return a shallow copy of the list

Example 5: how to make a list in python

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed data types
my_list = [1, "Hello", 3.4]

Example 6: python list

# example of list in python

myList = [9, 'hello', 2, 'python']

print(myList[0]) # output --> 9
print(myList[-3]) # output --> hello
print(myList[:3]) # output --> [9, 'hello', 2]
print(myList) # output --> [9, 'hello', 2, 'python']