create list in python

In Python, a list is created by enclosing a comma-separated sequence of values in square brackets []. For example, the following code creates a list of integers:

main.py
my_list = [1, 2, 3, 4, 5]
26 chars
2 lines

You can also create a list of strings:

main.py
fruits = ['apple', 'banana', 'orange', 'grape']
48 chars
2 lines

To access an element in a list, you can use square brackets [] with the index of the element you want to access. Note that the index starts at 0 in Python. For example, to access the second element in the my_list, you can use:

main.py
second_element = my_list[1]
28 chars
2 lines

You can also modify the elements of a list by assigning new values to specific indexes. For example, to change the third element in fruits to "pear", you can use:

main.py
fruits[2] = "pear"
19 chars
2 lines

Finally, you can add new elements to a list using the append() method:

main.py
my_list.append(6)
18 chars
2 lines

This will add 6 to the end of my_list.

related categories

gistlibby LogSnag